stay python A dictionary may contain several key value pairs or hundreds of key value pairs ,python Indicates that the key value pairs in the dictionary will be traversed , Dictionaries can be used to store all kinds of information , So we can traverse all key value pairs in the dictionary , You can also just iterate over keys or values .
First, let's look at a dictionary that stores information about Internet users , Now save the user name and name in the dictionary .
user_0={
'username':'efermi',
'first':'enrico',
'last':'fermi',
}
for key,value in user_0.items():
print(f"\nKey:{
key}")
print(f"Value:{
value}")
Key:username
Value:efermi
Key:first
Value:enrico
Key:last
Value:fermi
To write a traversal dictionary for loop , You can declare two variables , Used to store keys and values in key value pairs , These two variables can be any name .for The second part of the statement contains the dictionary name and method items(), It returns a list of key value pairs . Next for The loop assigns the amount of each key value pair to two specified variables in turn . Use these two variables to print each key and each value , And use \n Make sure to insert a blank line before each key value pair .
When we don't need dictionary values keys() It is useful to .
user_0={
'username':'efermi',
'first':'enrico',
'last':'fermi',
}
for key in user_0.keys():
print(key.title())
Username
First
Last
We use keys() Extract all the key values , And then assign it to the variable name, Let him print out .
Of course, we can also use in the process of traversal sorted() Sort .
user_0={
'username':'efermi',
'first':'enrico',
'last':'fermi',
}
for name in sorted(user_0.keys()):
print(f"{
name.title()},thank you .")
First,thank oyu.
Last,thank you.
Username,thank you
This makes the keys an alphabetical sort . And then output .
Traversal values and keys are the same for Statement to extract each value from the dictionary and assign the value to the variable in turn .
user_0={
'username':'efermi',
'first':'enrico',
'last':'fermi',
}
for value in user_0.values():
print(user_0.title())
Efermi
Enrico
Fermi