官术网_书友最值得收藏!

Dictionaries

A dictionary is a data type in Python, which consists of key value pairs and is enclosed in curly braces {}. Dictionaries are unordered and indexed by keys, where each key must be unique. These keys must be immutable type. Tuples can be used as keys if they contain only strings, numbers, or tuples.

Just a pair of braces creates an empty dictionary: { }. The main operations on a dictionary are storing a value with some key and extracting the value given to the key. It is also possible to delete a key value pair with del. If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key. Here is a small example using a dictionary:

>>> student = {'Name':'John', 'Age':25}
>>> student['Address'] = 'Mumbai'
>>> student
student = {'Name':'John', 'Age':25, 'Address':'Mumbai'}
>>> student['Age']
25
>>> del student['Address']
>>> student
student = {'Name':'John', 'Age':25}
>>> list(student.keys())
['Name', 'Age']
>>> sorted(student.keys())
['Age', 'Name']
>>> 'Name' in student
True
>>> 'Age' not in student
False

Arbitrary key and value expressions along with dictionary comprehensions are used to create dictionaries:

>>> {x: x**2 for x in (4, 6, 8)}
{4: 16, 6: 36, 8: 64}

When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:

>>> dict(John=25, Nick=27, Jack=28)
{'Nick': 27, 'John': 25, 'Jack': 28}
主站蜘蛛池模板: 临江市| 和顺县| 兴隆县| 南丹县| 禹州市| 米易县| 怀仁县| 五台县| 大厂| 隆林| 玛曲县| 尚义县| 平乐县| 陇西县| 贵港市| 株洲县| 绍兴县| 响水县| 合作市| 阳山县| 米泉市| 潮安县| 定西市| 香港 | 富顺县| 讷河市| 肥乡县| 汶上县| 柳林县| 崇义县| 肃宁县| 肥西县| 轮台县| 外汇| 唐河县| 安福县| 周口市| 井陉县| 宜春市| 喀喇沁旗| 宁德市|