Dictionaries are different from lists, tuples and strings. Lists, tuples and strings can be summarized as sequence types, which have the following characteristics:
- 1. Each element can be obtained by index
- 2. The default index value always starts from 0
- 3. You can get a set of elements within a range by slicing
- 4. There are many operators in common,
and the dictionary is a mapping type, which is completely different.
1. Create a dictionary
1.1 Commonly used creation methods
dict1 = {
'李宁':'云','耐克':'zoom','阿迪达斯':'boost','匹克':'态极'}
1.2 Create using tuples
dict2 = dict((('a',1),('b',2),('c',3),('d',4)))
1.3 Another way to create
dict3 = dict(马斯克 = '让编程改变世界',爱因斯坦 = '广义狭义相对论')
2. Modify the dictionary
dict3['李宁'] = '一切皆有可能'
# 如果字典中没有该元素,通过上述这种方式会新添加该元素到字典中
dict3['奋斗'] = '社会上容纳不了太多有理想的人'
3. Common methods
3.1 fromkeys(seq,val) method: create a new dictionary, use the elements in the sequence seq as the keys of the dictionary, val is the initial value corresponding to all the keys of the dictionary, val is optional
# 若没有设置val,默认为None
dict1 = {
}
dict1.fromkeys((1,2,3))
# 设置val为number,则创建的字典值为number
dict1.fromkeys((1,2,3),'number')
3.2 keys(): Get all the key values of the dictionary
dict2 = {
}
dict2 = dict2.fromkeys(range(30),'赞')
for each in dict2.keys():
print(each)
3.3 values(): get all the values of the dictionary
for each in dict2.values():
print(each)
3.4 items() method: print each item of the dictionary in the form of a tuple
for each in dict2.items():
print(each)
3.5 get(key,default) method: return the value of the specified key, if the value is not in the dictionary, return the default value, default is optional
# dict2字典中只有30个元素,索引值0~29,没有30,因此返回一个None
print(dict2.get(30))
print(dict2.get(29))
3.6 in/not in: Determine whether the key is in the dictionary¶
32 in dict2
29 in dict2
3.7 copy(): This is a shallow copy, and direct equality is not the same thing
a = {
1:'one',2:'two'}
# 浅拷贝
b = a.copy()
# 通过打印首地址来确认
print(id(a))
print(id(b))
# 可以发现不是相同的
# 深拷贝
c = a
print(id(c))
print(id(a))
# 可以发现这是一致的
3.8 pop(key,default): Delete the value corresponding to the given key key of the dictionary, and the return value is the deleted value. The key value must be given. Otherwise, the default value is returned.
dict2.pop(27)
3.9 popitem(): Return and delete the last pair of keys and values in the dictionary.
dict2.popitem()
3.10 setdefault(key,default): similar to get(), but if the key does not exist in the dictionary, the key will be added and the value will be set to default
dict2.setdefault(26,'woaini')
3.11 update(dict2): update the key/value pairs of dictionary dict2 to dict
dict2.update({
99:'kk'})