I. Python's Dictionary
In the development process of the project, if you encounter the content of the mapping relationship can be considered to use Python in the dictionary to store the data, the data before the colon in the dictionary is called [key], the data after the colon is called [value].
Second, the use of Python dictionaries
2.1 Definition of Python
Definition of #Python dictionary Dictionary name={linchpin1:(be) worth1,linchpin2:(be) worth2,linchpin3:(be) worth3,...} Example of a #Python dictionary definition: nameDic={'Zhang San':26,'Li Si':23,'Wang Wu':25,}
2.2. Getting the value of a Python dictionary
#Get Python's value definitions (be) worth=Dictionary name[linchpin] # Get Python value example: info1=nameDic['Zhang San'] info2=nameDic['Li Si'] info3=nameDic['Wang Wu']
2.3. Modifying Python dictionary values
#Modify the value of a Python dictionary Dictionary name[linchpin]=new value # Example of modifying the value of a Python dictionary: nameDic['Zhang San']=36 nameDic['Li Si']=32 nameDic['Wang Wu']=30
2.4 Delete the contents of the specified key of the Python dictionary
# Delete the contents of the specified key of a Python dictionary del Dictionary name['key'] # Delete Python dictionary specified key content example: del nameDic['Zhang San'] del nameDic['Li Si'] del nameDic['Wang Wu']
III. Python dictionary traversal
favorite_languages={ 'jen':'python', 'sarah':'c', 'edward':'ruby', 'phil':'C#', 'jone':'java', 'sarah':'c', }
3.1. Getting all the keys of a dictionary
# Get all keys of the dictionary way 1 for key in Dictionary name: print(key) # Get all keys of the dictionary way 2 for key in Dictionary name.keys(): print(key) # Get all keys of a dictionary mode 1 example: print('\n loop outputs all keys of the dictionary') for key in favorite_languages: print(key) # Get all keys of the dictionary Mode 2 Example: print('\n output all keys and values') for item in favorite_languages.keys(): print(item,favorite_languages[item])
3.2. Getting all the values of a dictionary
# Get all the values of the dictionary for value in Dictionary name.values(): print(value) # Get all values of the dictionary example: print('\n loop outputs all values of the dictionary') for value in favorite_languages.values(): print(value)
3.3. Getting the keys and values of a dictionary
# Get the keys and values of the dictionary for item in Dictionary name.items(): print(item) # Get the key and value examples of a dictionary: print('\n loop outputs the keys and values of the dictionary') for item,value in favorite_languages.items(): print(item,value)
3.4. Python Dictionary Iteration Example
to this article on the detailed Python traversal of the dictionary keys and values of the article is introduced to this, more related Python traversal of the dictionary keys and values of the content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!