The dictionary consists of curly braces and key-value pairs, characterized by unordered, key-unique
1. Creation of dictionaries
#直接创建字典dic1 ={' name ': ' A ', ' Age ': 20}
#通过dict创建字典, the output is {' name ': ' A ', ' Age ': 20}dic2=dict ((' Name ', ' a '), (' Age ', ') ') print (DIC2) dic3=dict ([' Name ', ' a '],[' Age ', []]) print (DIC3)
2. Additions and modifications to the dictionary
dic1={' name ': ' A '}dic1[' age ']=20print (DIC1) #如果字典中存在age, then change the value of age to 20 and, if it does not exist, add ' age ': 20age=dic1.setdefault (' Age ' Print (age) #键存在, do not change, return the value corresponding to the corresponding key in the dictionary, the output is 20hobby=dic1.setdefault (' hobby ', ' Sport ') print (hobby) #键不存在, in the dictionary to add a new key value pair and returns the corresponding value, the output is sport
3. The dictionary query, through the key to find
dic3={' age ': +, ' name ': ' A ', ' hobby ': ' Sport}print (dic3[' name ') ' #输出aprint (Dic3.keys ()) #输出dict_keys ([' Age ', ' name ', ' Hobby '), other similar print (List (Dic3.keys ())) #输出 [' Age ', ' name ', ' Hobby ']print (List (Dic3.values ())) #输出 [a ', ' a ', ' sport '] Print (List (Dic3.items ())) #输出 [(' Age ', ' a '), (' Name ', ' a '), (' Hobby ', ' sport ')] #更新字典dic4 the ={' age ': ' The ' name ': ' A ', ' hobby ': ' Sport '}dic5={' 1 ': ' 111 ', ' name ': ' 222 '}dic4.update (dic5) print (DIC4) #输出 {' Age ': ' ' name ': ' 222 ', ' hobby ': ' Sport ', ' 1 ' : ' 111 '}print (DIC5) #输出 {' 1 ': ' 111 ', ' name ': ' 222 '}
4. Deletion of dictionaries
DIC5 = {' name ': ' A ', ' age ': $, ' hobby ': Sport}dic5.clear () # Empty the Dictionary del dic5[' name '] #删除字典中指定键值对print (Dic5.pop (' age ')) #删除字典 Specifies the key-value pair and returns the value of the key-value pair, you should output 20a = Dic5.popitem () #随机删除某组键值对 and return the value in tuples del dic5 #删除整个字典
5. Other ways to create dictionaries
Dic6=dict.fromkeys ([' host1 ', ' host2 ', ' host3 '], ' test ') print (dic6) #输出 {' host3 ': ' Test ', ' host1 ': ' Test ', ' host2 ': ' Test ' '}dic6=dict.fromkeys ([' host1 ', ' host2 ', ' host3 '],[' test1 ', ' tets2 ']) print (dic6) #{' host2 ': [' test1 ', ' tets2 '], ' host3 ': [' test1 ', ' tets2 '], ' host1 ': [' test1 ', ' tets2 ']}dic6[' host2 '][1]= ' test3 ' Print (dic6) #{' host3 ': [' test1 ', ' test3 '], ' Host2 ': [' test1 ', ' test3 '], ' host1 ': [' test1 ', ' Test3 ']}, not only does this change the value of Host2
6. The traversal of a dictionary
Can take advantage of a for loop
DIC5 = {' name ': ' A ', ' age ': $, ' hobby ': ' Sport '} for I in DIC5: print (I,dic5[i])-I,v in Dic5.items (): Print (i , V)
Python Basic Learning 5----Dictionary