Python study notes-the common grammar of the dictionary

Dictionary grammar

1. Extraction of dictionary data

#List uses offset to extract, dictionary uses key to extract

>>> group = {'Master': 'Tang Sanzang', 'Master Brother': 'Sun Xingzhe', 'Second Brother': 'Zhu Bajie', 'Sha Shijie': 'Sha Monk'

>>> print (group ['师 师'])

Tang Sanzang

 

2. Modification of dictionary data

>>> group = {'Master': 'Tang Sanzang', 'Master Brother': 'Sun Xingzhe', 'Second Brother': 'Zhu Bajie', 'Sha Shijie': 'Sha Monk'}

>>> group ['师 师'] = '唐 玄奘'

>>>print(group)

{'Master': 'Tang Xuan Zang', 'Master Brother': 'Sun Xingzhe', 'Second Brother': 'Zhu Bajie', 'Sha Shijie': 'Sand Monk'}

 

3. Increase of dictionary data

>>> group = {'Master': 'Tang Sanzang', 'Master Brother': 'Sun Xingzhe', 'Second Brother': 'Zhu Bajie', 'Sha Shijie': 'Sha Monk'}

>>> group ['白 龙马'] = '奥烈'

>>>print(group)

{'Master': 'Tang Sanzang', 'Master Brother': 'Sun Xingzhe', 'Second Brother': 'Zhu Bajie', 'Sha Shijie': 'Sha Monk', 'White Dragon Horse': 'Ao Lie'}

 

4. Deletion of dictionary data

>>> group = {'Master': 'Tang Sanzang', 'Master Brother': 'Sun Xingzhe', 'Second Brother': 'Zhu Bajie', 'Sha Shijie': 'Sha Monk'}

>>> del group ['Master']

>>>print(group)

{'Master Brother': 'Sun Xingzhe', 'Second Brother': 'Zhu Bajie', 'Sand Brother Sha': 'Sand Monk'}

 

5. Extract all the keys in the dictionary

dict.keys()

>>> group = {'Master': 'Tang Sanzang', 'Master Brother': 'Sun Xingzhe', 'Second Brother': 'Zhu Bajie', 'Sha Shijie': 'Sha Monk'

>>>print(group.keys())

dict_keys (['Master', 'Master Brother', 'Second Brother', 'Sister Sha'])

 

#Print out all the keys of the dictionary, but they are all in the form of tuples

 

>>> group = {'Master': 'Tang Sanzang', 'Master Brother': 'Sun Xingzhe', 'Second Brother': 'Zhu Bajie', 'Sha Shijie': 'Sha Monk'

>>>print(list(group.keys()))

['Master', 'Master Brother', 'Second Brother', 'Brother Sha']

 

#Use the list () function to convert tuples into a list

 

6. Extract all the values ​​in the dictionary

dict.values()

>>> group = {'Master': 'Tang Sanzang', 'Master Brother': 'Sun Xingzhe', 'Second Brother': 'Zhu Bajie', 'Sha Shijie': 'Sha Monk'

>>>print(group.values())

dict_values ​​(['Tang Sanzang', 'Sun Xingzhe', 'Zhu Bajie', 'Sand Monk'])

 

7. Extract all key-value pairs in the dictionary

dict.items()

>>> group = {'Master': 'Tang Sanzang', 'Master Brother': 'Sun Xingzhe', 'Second Brother': 'Zhu Bajie', 'Sha Shijie': 'Sha Monk'

>>>print(group.items())

dict_items ([('Master', 'Tang Sanzang'), ('Master Brother', 'Sun Xingzhe'), ('Second Brother', 'Zhu Bajie'), ('Sha Shidi', 'Sha Monk')))

Guess you like

Origin www.cnblogs.com/zxc01/p/12687881.html