Python basic operations_dictionary traversal
Python basic operations_dictionary traversal
2.3 Traverse the dictionary
Ways to traverse the dictionary: 1 Traverse all key-value pairs in the dictionary
2 Traverse the keys of the dictionary
3 Traverse the values of the dictionary
2.3.1 Traverse all key-value pairs
user_0 = {
'username':'efermi',
'first':'enrico',
'last':'fermi',
}
Get all the information in the dictionary user_0 for loop
Keys and values can be any names (variables): k, v
The names of keys and values can be named according to the actual situation, so that they are easy to understand.
The items() function returns an iterable (key, value) tuple as a list.
Store key-value pairs in the dictionary as tuples, and store many tuples in lists.
You can use the list function to convert the iterable sequence returned by items into a list
list_1 = user_0.items()
list(list_1)
result:
Out[2]: [('username', 'efermi'), ('first', 'enrico'), ('last', 'fermi')]
Return value: [('username', 'efermi'), ('first', 'enrico'), ('last', 'fermi')]
for key,value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
result:
Key: username
Value: efermi
Key: first
Value: enrico
Key: last
Value: fermi
or
for k,v in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
result:
Key: last
Value: fermi
Key: last
Value: fermi
Key: last
Value: fermi
NOTE: The order in which key-value pairs are returned may differ from the order in which they are stored, because Python does not care about the order in which key-value pairs are stored,
And only track the relationship between keys and values
favorite_languages = {
'jen':'[python](/search?q=python)',
'sarah':'c',
'edwaid':'[ruby](/search?q=ruby)',
'phil':'python',
}
The names of keys and values can be named according to the actual situation, so that they are easy to understand.
That is, using descriptive statements for keys and values makes it easier for people to understand what operations are being done in the for loop.
for name,language in favorite_languages.items():
print(name.title() + "'s favorite languages is " +
language.title() + ".")
result:
Jen's favorite languages is Python.
Sarah's favorite languages is C.
Edwaid's favorite languages is Ruby.
Phil's favorite languages is Python.
2.3.2 Key method keys() in variable dictionary
The keys function is Python's dictionary function, which returns an iterable sequence composed of all keys in the dictionary.
Use keys() to get all keys in the dictionary.
Use the list() function to convert the iterable sequence returned by the keys() function into a list
favorite_languages = {
'jen':'python',
'sarah':'c',
'edwaid':'ruby',
'phil':'python',
}
for name in favorite_languages.keys():
print(name.title())
# 这四行代码等价
for name in favorite_languages:
print(name.title())
result:
Jen
Sarah
Edwaid
Phil
Reason: When traversing the dictionary, all keys will be traversed by default
The method keys() is the displayed traversal key
Store keys in a dictionary into a list of names
names = []
names_1 = list(favorite_languages.keys())
for name in favorite_languages:
t_names = name
names.append(t_names)
print(name.title())
print(names)
print(names_1)
result:
Jen
Sarah
Edwaid
Phil
['jen', 'sarah', 'edwaid', 'phil']
['jen', 'sarah', 'edwaid', 'phil']
Example using key traversal: using the current key to access the value associated with it
favorite_languages = {
'jen':'python',
'sarah':'c',
'edwaid':'ruby',
'phil':'python',
}
friends = ['phil','sarah']
for name in favorite_languages.keys():
print(name.title())
if name in friends:
print(" Hi " + name.title() +
", I see your favorite language is " +
favorite_languages[name].title() + "!")

result:
Jen
Sarah
Hi Sarah, I see your favorite language is C!
Edwaid
Phil
Hi Phil, I see your favorite language is Python!
Use keys() to determine whether a person has been surveyed
favorite_languages = {
'jen':'python',
'sarah':'c',
'edwaid':'ruby',
'phil':'python',
}
if 'erin' not in favorite_languages.keys():
print("Erin,please take our poll!")
result:
Erin,please take our poll!
2.3.3 The sorted function traverses all keys in the dictionary in order
favorite_languages = {
'jen':'python',
'sarah':'c',
'edwaid':'ruby',
'phil':'python',
}
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
result:
Edwaid, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.
2.3.4 Traverse all values in the dictionary using values()
values() return value: It returns an iterable sequence composed of all the values in the dictionary.
Use list to remove the dict_value prefix and convert it to a list
favorite_languages = {
'jen':'python',
'sarah':'c',
'edwaid':'ruby',
'phil':'python',
}
print("The following languages have been mentioned: ")
for language in favorite_languages.values():
print(language.title())
result:
The following languages have been mentioned:
Python
C
Ruby
Python
To remove duplicate values, consider the set sum
print("The following languages have been mentioned: ")
for language in set(favorite_languages.values()):
print(language)
list_languages = list(favorite_languages.values())
print(type(list_languages))
print(list_languages)
result:
The following languages have been mentioned:
python
ruby
c
<class 'list'>
['python', 'c', 'ruby', 'python']
python,c,ruby,python
Another way to iterate over values
value = favorite_languages.values()
print(",".join(i for i in value))
result:
python,c,ruby,python
2-4 Nesting
Definition: Storing a sequence of dictionaries in a list, or a list as a value in a dictionary, is called nesting
2-4-1 Dictionary list Save dictionary into list
4. List of stored dictionaries
alien_0 = {'color':'green','points':5}
alien_1 = {'color':'yellow','points':10}
alien_2 = {'color':'red','points':15}
aliens = [alien_0,alien_1,alien_2]
for alien in aliens:
print(alien)
result:
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
Aliens have codes automatically generated
Create an empty list for storing aliens
aliens = []
Create 30 green aliens
for alien_number in range(30):
new_alien = {'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)
# 显示前5个外星人
for alien in aliens[:5]:
print(alien)
print(".......")
result:
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
.......
Shows multiple aliens created
print("\nTotal number of aliens: " + str(len(aliens)))
result:
Total number of aliens: 30
Aliens all have the same characteristics. Each alien in python is independent, so we can modify each alien.
Modify the first 3 alien characteristics
Create an empty list for storing aliens
aliens = []
Create 30 green aliens
for alien_number in range(30):
new_alien = {'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)
for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
Show top 5 aliens
for alien in aliens[:5]:
print(alien)
print(".......")
result:
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
.......
expand further
Create an empty list to store aliens aliens = []
aliens = []
Create 30 green aliens
for alien_number in range(30):
new_alien = {'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)
for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['speed'] = 'fast'
alien['points'] = 15
Show top 5 aliens
for alien in aliens[:10]:
print(alien)
print(".......")
result:
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
.......
Application field: Create a dictionary for each user on the website and store the dictionary in a list
(The structure of each dictionary is the same)
Iterate through the list to process data
2.4.2 Storing a list in a dictionary means putting a list in a dictionary
5. Dictionary to store lists
Store information about pizza ordered
pizza = {
'crust':'thick',
'toppings':['mushrooms','extra cheese'],
}
Overview of the pizza ordered
print("You ordered a " + pizza['crust'] + "-crust pizza " +
"With the following toppings: ")
for topping in pizza['toppings']:
print('\t' + topping)
result:
You ordered a thick-crust pizza With the following toppings:
mushrooms
extra cheese
A key is associated with multiple values
favorite_languages = {
'jen':['python','ruby'],
'sarah':['c'],
'edwaid':['ruby','go'],
'phil':['python','haskell'],
}
for name,languages in favorite_languages.items():
if len(languages) == 1:
print("\n" + name.title() + "'s favorite language is " + languages[0].title())
# Note that when there is only one element in the list, you have to use the subscript 0 to get the last element
else:
print("\n" + name.title() + "'s favorite languages are: ")
for language in languages:
print("\t" + language.title())
result:
Jen's favorite languages are:
Python
Ruby
Sarah's favorite language is C
Edwaid's favorite languages are:
Ruby
Go
Phil's favorite languages are:
Python
Haskell
Note: Lists and dictionaries should not be nested too many levels
If there are too many, you should consider a simpler method
6-4-3 Store dictionary in dictionary
6. Dictionary that stores dictionaries
users = {
'aeinstein':{
'first':'albert',
'last':'einstein',
'location':'princeton',
},
'mcurie':{
'first':"marie",
'last':'curie',
'location':'paris',
},
}
for username,user_info in users.items():
print("\nUsername: " + username)
full_name = user_info['first'] + " " + user_info['last']
location = user_info['location']
print("\tFull name: " + full_name.title())
print("\tLocation: " + location.title())

result:
Username: aeinstein
Full name: Albert Einstein
Location: Princeton
Username: mcurie
Full name: Marie Curie
Location: Paris
Summary:
1. Dictionary traversal method: items() method: key-value pair traversal, the returned value is an iterable sequence, the list() function can convert it into a list
keys() method: key traversal, the returned value It is an iterable sequence. The list() function can convert it into a list.
values() method: value variable. The return value is an iterable sequence. The list() function can convert it into a list.
2. Nesting: In a list Place a dictionary for objects with the same attributes.
Place a list in a dictionary for objects with the same key.
Place a location in a dictionary for copying objects.
3. In Python, for the iterable built-in data type tuple, if the string is placed In an iterable object , the last string will be a character variable, because a single string is also an iterable object
. Example:
list_2 = ('Hello!')
for ele in list_2:
print(ele)
result:
H
e
l
l
o
!