- Daniel Arbuckle's Mastering Python
- Daniel Arbuckle
- 250字
- 2021-07-02 21:09:31
Dictionaries
The first data structure we're going to look at is Python's dictionary. A dictionary consists of any number of key-value pairs. The key can be used to get or set the value or remove the pair from the dictionary entirely.
There are several ways to create a dictionary in Python. The simplest is to use a dictionary expression, which is just a pair of curly brackets surrounding the key-value pairs we want in the dictionary. Each key-value pair is marked with a colon between the key and value, and each pair is separated by a comma, as shown in the following code example:
example_dict = {'a' :1, 'b' :2, 'c' :3}
When this expression runs, the result is a dictionary object containing the keys and their values. We can also use the dict class to create dictionary objects:
another_dict = dict()
If we don't want to use the special syntax to access one of the stored values in a dictionary, we use a lookup expression. This means that we place square brackets containing the key we want to look up after an expression that gives us the dictionary. Usually, this means, the name of the variable containing the dictionary, an open square bracket, a sub-expression that gives us the key, and then a closing square bracket:
example_dict['b'] 2
We can also use the dict.get function if we prefer not to use the special syntax:
example_dict.get('c') 3
- 精通Nginx(第2版)
- 復(fù)雜軟件設(shè)計(jì)之道:領(lǐng)域驅(qū)動(dòng)設(shè)計(jì)全面解析與實(shí)戰(zhàn)
- AIRAndroid應(yīng)用開發(fā)實(shí)戰(zhàn)
- Julia機(jī)器學(xué)習(xí)核心編程:人人可用的高性能科學(xué)計(jì)算
- C/C++常用算法手冊(cè)(第3版)
- UI智能化與前端智能化:工程技術(shù)、實(shí)現(xiàn)方法與編程思想
- PostgreSQL 11從入門到精通(視頻教學(xué)版)
- 老“碼”識(shí)途
- Mastering Yii
- Java 9模塊化開發(fā):核心原則與實(shí)踐
- HDInsight Essentials(Second Edition)
- Spring Data JPA從入門到精通
- Visual Basic程序設(shè)計(jì)基礎(chǔ)
- 軟件測(cè)試項(xiàng)目實(shí)戰(zhàn)之功能測(cè)試篇
- Java項(xiàng)目驅(qū)動(dòng)開發(fā)教程