I. Introduction to the Dictionary
1. A dictionary is another mutable container model and can store any type of object.
2. Each key value of the dictionary key-value pairs with a colon : Split, each key-value pair is separated by commas, and the entire dictionary is included in the curly braces {}, as shown in the following format:D = { key1 : value1, key2 : value2 }
3. The dictionary is unordered
4. The key in the dictionary is unique, if key is already present, overwrite the value of key, and if key does not exist, insert a key value pair
5. The value can take any data type, but the key must be immutable, such as a string, a number, or a tuple
Second, the use of the dictionary
data = {' name ': ' Zhang San ',
' Age ': 18,
' Sex ': ' Woman '}
1. Increase
data[' email ']= ' [email protected] '
Data.setdefault (' age ', $) #setdefault这种方式, if key already exists, regardless of it, if key does not exist, add
2. Modifications
data[' sex ']= ' man '
3. Delete
Data.pop (' sex ') #指定的key来删除, key does not exist will error
del data[' sex '] #指定的key来删除, key does not exist will error
4. Take the value
data[' sex ']
Data.get (' sex1 ', ' haha ') #返回指定键的值 if the value does not return the default value in the dictionary (' haha ')
5. Other
Data.clear () #清空字典
Data.update (DATA2) #把字典2的键值对加入到字典里
Data.items () #以列表返回可遍历的 (key, value) tuple array
Data.keys () #以列表返回一个字典所有的键
Data.valus #以列表返回一个字典所有的值
Data.popitem () #随机返回并删除字典中的一对键和值
6. How to efficiently cycle a dictionary:
For k in data:
Print (K,data.get (k))
A Dictionary of Python