Definition of a dictionary
A dictionary is a series of key-value pairs, which are represented by a series of key-value pairs placed in {}
info = {'first_name':'yueshang','last_name ':'QIN',' age':' ' city':'KunMing'}
Dictionary increment, delete, change, check
Add new elements
Specifies the dictionary name, the key enclosed in square brackets, and the associated value
info['sex']='man'
modifying elements
Specifies the dictionary name, the key enclosed in square brackets, and the new value associated with the key
info['sex']='Woman'
Inquire
Specify the dictionary name and the key that is enclosed in parentheses
Print (info['sex')
In practice, it is possible that a dictionary contains thousands of key-value pairs, so a traversal is required to fully access the key value
Traverse all key values to items ()
for inch Info.items (): Print ("\nkey:" + key) Print ("\nvalue:" + value)
Traverse all keys
for inch Info.keys (): Print (key)
Traverse All Values
for inch info.values (): Print (value)
Note: When traversing, if you need to sort the traversed keys, then use sorted (). Values are the same
Use of the Set () method: The Set () method can repeat the element
Set () case
Letter = {'1':'A','2':'B','3':'C','4':'A'} forIinchSet (Letter.values ()):Print(i)
Print Result: C A B
Delete
Use the DEL statement to delete the corresponding key-value pair
del info['sex']
Deleted key-value pairs disappear forever.
Nesting
Sometimes you need to store a series of dictionaries in a list, or you can store a list in a dictionary, which is called nesting.
To store a dictionary in a list
Now there are three athletes in the country, with a list to store information about the athletes in each country.
America_player = {'name':'Tom',' Age': 24}china_player= {'name':'Zhangsan',' Age': 27}japan_player= {'name':'Jinshang',' Age': 25}players=[America_player,china_player,japan_player] forPalyerinchPlayers:Print(Palyer)
Nesting lists in a dictionary
Now there are 2 people, each with their own favorite fruit list, we need to store all this information, then use a dictionary, where elements are a list.
Favorite_fruits = { 'Zhangsan':['Apple','Pear'], 'Lisi':['Orange','Apple']} forName,fruitsinchFavorite_fruits.items ():Print("\ n"+name.title () +"' s favorite fruits is:") forFruitinchFruits:Print("\ n"+fruit.title ())
Nesting dictionaries in a dictionary
Here are 2 Web sites, each corresponding to a different user name, the dictionary stored in a dictionary to meet this requirement
Users = { 'website1':{ 'name':'Zhangsan', 'Password':'123' }, 'Website2': { 'name':'Lisi', 'Password':'456' }} forWebsite,logininfoinchUsers.items ():Print("\nwebsite:"+Website)Print("\tusername:"+logininfo['name']) Print("\tpassword:"+ logininfo['Password'])
"Python" dictionary ~ in-depth article