目录
5.3 遍历字典中所有的值(values()方法,函数set())
1. 字典的创建和访问字典中的值
在Pyhton中,字典是一系列键值对,每个键都与一个值相关联,可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。在Python中,字典用放在花括号{}中的一系列键值对表示,如下面就是一个字典:
alien_0 = {'color': 'green', 'points': 5}
键值对是两个相关联的值,指定键时,Python将返回与之相关联的值。键和值之间用冒号分隔,而键值对之间用逗号分隔。
要获取与键相关联的值,可依次指定字典名和放在方括号内的键,如下所示:
alien_0 = {'color': 'green'}
print(alien_0['color'])
这将返回字典alien_0中与键'color'相关联的值:
green
2. 在字典中添加键值对
字典是一种动态结构,可随时在其中添加键值对。要添加键值对,可依次指定字典名、用方括号括起的键和相关联的值,如下所示:
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
在这段代码中,首先定义了一个字典alien_0,然后在里面添加了两个键值对,其输出为:
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
这个字典的最终版本包含四个键值对。注意,在Python3.6及更早的版本中,键值对的排列顺序与添加顺序不同,及在字典中键值对的排列顺序是无序的。Python不关心键值对的添加顺序,而只关心键和值之间的关联关系。而在Python3.7及以上版本中,字典中键值对的顺序是有序的。
3. 修改字典中的值
要修改字典中的值,可依次指定字典名、用方括号括起的键以及与该键相关联的新值,如下所示:
alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".")
则输出结果如下:
The alien is green.
The alien is now yellow.
4. 使用del语句删除键值对
对于字典中不再需要的信息,可使用del语句将相应的键值对彻底删除。使用del语句时,必须指定字典名和要删除的键:
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
在上面这段代码中,将键'points'从字典alien_0中删除,同时删除与这个键相关联的值,其输出结果如下:
{'color': 'green', 'points': 5}
{'color': 'green'}
5. 遍历字典
Python支持对字典的遍历,并且有多种遍历字典的方式:可遍历字典的所有键值对、键或值。注意,在Python3.7及更高版本中,由于字典的排列顺序是有序的,因此遍历返回的值也是按顺序的。
5.1 遍历字典中所有的键值对(items()方法)
下面的字典存储一名用户的用户名、名和姓:
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
可以使用for循环来遍历这个字典:
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
在上面这段代码中,要编写用于遍历字典的for循环,可声明两个变量,用于存储键值对中的一对键和值。for语句的第二部分包含字典名和方法items(),它返回一个键值对列表。接下来,for循环依次将每个键值对存储到指定的两个变量中,输出结果如下所示:
Key: username
Value: efermi
Key: first
Value: enrico
Key: last
Value: fermi
5.2 遍历字典中所有的键(keys()方法)
在不需要使用字典中的值时,方法keys()很有用:
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys():
print(name.title())
上面的代码提取字典中的所有键,并依次将它们存储到变量name中,输出结果如下:
Jen
Sarah
Edward
Phil
注意,遍历字典时,会默认遍历所有的键,因此,如果将上述代码中的for name in favorite_languages.keys(): 替换为for name in favorite_languages:,则输出结果不变。
5.3 遍历字典中所有的值(values()方法,函数set())
在不需要使用字典中的键时,方法values()很有用:
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("The following languages have been mentioned:")
for language in favorite_languages.values():
print(language.title())
这条for语句提取字典中的每个值,并将它们依次存储到变量language中。输出结果如下:
The following languages have been mentioned:
Python
C
Ruby
Python
这种做法提取字典中所有的值,而没有考虑重复。使用函数set()来生成一个列表,生成的列表中每个元素都是独一无二的:
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
print(language.title())
此时输出的结果是一个不重复的列表,如下所示:
The following languages have been mentioned:
Ruby
Python
C
6. 嵌套
有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套。你可以在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典。
6.1 在列表中嵌套字典
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)
此时的输出结果为:
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
6.2 在字典中嵌套列表
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
print("You ordered a " + pizza['crust'] + "-crust pizza " + "with the following toppings:")
for topping in pizza['toppings']:
print("\t" + topping)
此时的输出结果为:
You ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese
每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表,下面是一个经典的例子:
favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
print("\n" + name.title() + "'s favorite languages are:")
for language in languages:
print("\t" + language.title())
此时的输出结果为:
Jen's favorite languages are:
Python
Ruby
Sarah's favorite languages are:
C
Edward's favorite languages are:
Ruby
Go
Phil's favorite languages are:
Python
Haskell
6.3 在字典中嵌套字典
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())
其输出结果为:
Username: aeinstein
Full name: Albert Einstein
Location: Princeton
Username: mcurie
Full name: Marie Curie
Location: Paris