Python编程:从入门到实践-字典
-
使用字典
在Python中,字典时一系列键-值对,每个键都与一个值相关联。可以使用键来访问与之相关联的值。与键想关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何Python对象用作字典中的值。
在Python中,字典用放在花括号{}中的一系列键-值对表示。
1 #!/usr/bin/env python 2 #-*- encoding:utf-8 -*- 3 alient_0 = {'color': 'green', 'point':5} 4 print(alient_0['color']) 5 print(alient_0['point'])
C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/demo.py
green
5
访问字典中的值
要获取与键相关联的值,可依次指定字典名和放在方括号内的键
>>> alien_0 = {'color': 'green'}
>>> print(alien_0['color'])
green
>>>
首先定义一个字典,然后从这个字典中获取与键'points' 相关联的值,并将这个值存储在变量new_points中。接下来,将这个整数转换为字符串,并打印一条消息
>>> alien_0 = {'color': 'green', 'points': 5}
>>> new_points = alien_0['points']
>>> print("You just earned " + str(new_points) + " points!")
You just earned 5 points!
添加键-值对
字典是一种动态结构,可随时在其中添加键-值对。要添加键值对,可一次指定字典名、用方括号括起的键和相关联的值
>>> print(alien_0)
{'color': 'green', 'points': 5}
>>> alien_0['x_position'] = 0
>>> alien_0['y_position'] = 25
>>> print(alien_0)
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
>>>
创建一个空字典
在空字典添加键-值对。
>>> alien_0 = {}
>>> alien_0['color'] = 'green'
>>> alien_0['points'] = 5
>>>
>>> print(alien_0)
{'color': 'green', 'points': 5}
修改字典中的值
修改字典中的值
>>> alien_0 = {'color': 'green'}
>>> print("The alien is " + alien_0['color'] + ".")
The alien is green.
>>>
>>> alien_0['color'] = 'yellow'
>>> print("The alien is now " + alien_0['color'] + ".")
The alien is now yellow.
>>>
例子:对一个能够以不同速度移动的外星人的位置进行跟踪。我们将存储该外星人的当前速度,并据此确定该外星人将向右移动多远
1 #!/usr/bin/env python 2 alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'} 3 print("Original x-position: " + str(alien_0['x_position'])) 4 # 向右移动外星人 5 # 据外星人当前速度决定将其移动多远 6 if alien_0['speed'] == 'slow': 7 x_increment = 1 8 elif alien_0['speed'] == 'medium': 9 x_increment = 2 10 else: 11 # 这个外星人的速度一定很快 12 x_increment = 3 13 # 新位置等于老位置加上增量 14 alien_0['x_position'] = alien_0['x_position'] + x_increment 15 print("New x-position: " + str(alien_0['x_position']))
使用一个if-elif-else 结构来确定外星人鹰向右移动多远,并将这个值存储在变量x_increment中。如果速度为'medium',将向右移动两个单位。
删除键-值对
使用del语句将相应的键-值对彻底删除。
>>> print(alien_0)
{'color': 'yellow'}
>>> alien_0 = {'color': 'green', 'points':5}
>>> print(alien_0)
{'color': 'green', 'points': 5}
>>>
>>>
>>> del alien_0['points']
>>> print(alien_0)
{'color': 'green'}
>>>
由类似对象组成的字典
字典存储的是一个对象的多种信息,也可以使用字典来存储众多对象的同一种信息。
#!/usr/bin/env python
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python', #最后一个键-值对后面也加上逗号,为以后在下一行添加键-值对做好准备
}
print("Sarah's favorite language is " + favorite_languages['sarah'].title() + ".")
-
遍历字典
遍历字典的方式:可遍历字典的所有键-值对、键和值
遍历所有的键-值对
方法items() 返回一个键-值对列表,for循环一次将每个键-值对存储在指定的两个变量中。使用这两个变量来打印每个键及其相关联的值。
1 #!/usr/bin/env python 2 3 user_0 = { 4 'username': 'efermi', 5 'first': 'enrico', 6 'last': 'fermi', 7 } 8 9 for key, value in user_0.items(): 10 print("\nKey: " + key) 11 print("Value: " + value)
注意,即便遍历字典时,键-值对的返回顺序也与存储顺序不同。Python不关心键-值对的存储顺序,而只跟踪键和值之间的关联关系
1 C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/user.py 2 3 Key: username 4 Value: efermi 5 6 Key: first 7 Value: enrico 8 9 Key: last 10 Value: fermi
Python遍历字典的每个键-值对,并将键存储在变量name中,而将值存储在变量language中。
1 #!/usr/bin/env python 2 favorite_languages = { 3 'jen': 'python', 4 'sarah': 'c', 5 'edward': 'ruby', 6 'phil': 'python', #最后一个键-值对后面也加上逗号,为以后在下一行添加键-值对做好准备 7 } 8 9 for name, language in favorite_languages.items(): 10 print(name.title() + "'s favorite language is " + 11 language.title() + ".")
1 C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/favorite_languages.py 2 Jen's favorite language is Python. 3 Sarah's favorite language is C. 4 Edward's favorite language is Ruby. 5 Phil's favorite language is Python.
遍历字典中的所有键
方法keys(),提取字典favorite_languages中的键,并将它们存储在变量name中。
#!/usr/bin/env python
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python', #最后一个键-值对后面也加上逗号,为以后在下一行添加键-值对做好准备
}
for name in favorite_languages.keys():
print(name.title())
遍历字典时,会默认遍历所所有的键。将for name in favorite_languages.keys(): 替换为for name in favorite_languages: ,输出将不变。
C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/favorite_languages.py Jen Sarah Edward Phil
在循环中,可使用当前键来访问与之相关联的值。创建一个列表,其中包含要通过打印消息,指出其喜欢的语言的朋友。
#!/usr/bin/env python
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': '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() + "!")
运行结果
C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/favorite_languages.py Jen Sarah Hi Sarah, I see your favorite language is C! Edward Phil Hi Phil, I see your favorite language is Python!
还可以使用keys()确定某个人是否接受了调查。
#!/usr/bin/env python
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python', #最后一个键-值对后面也加上逗号,为以后在下一行添加键-值对做好准备
}
if 'erin' not in favorite_languages.keys():
print("Erin, please take our poll!")
方法keys() 并非只能用于遍历;实际上,它返回一个列表,其中包含字典中的所有键。代码只是核实'erin' 是否包含在这个列表中。
按顺序遍历字典中的所有键
要以特定的顺序返回元素,一种方法是在for循环中对返回的键进行排序,可使用函数sorted() 来获得按特定顺序排列的键列表的副本。
#!/usr/bin/env python
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
1 C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/favorite_languages.py 2 Edward, thank you for taking the poll. 3 Jen, thank you for taking the poll. 4 Phil, thank you for taking the poll. 5 Sarah, thank you for taking the poll.
遍历字典中的所有值
如果只需要字典包含的值,可使用方法values(),它返回一个值的列表,而不包含任何键。
#!/usr/bin/env python
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())
1 C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/favorite_languages.py 2 The following languages have been mentioned: 3 Python 4 C 5 Ruby 6 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())
1 C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/favorite_languages.py 2 The following languages have been mentioned: 3 C 4 Ruby 5 Python
-
嵌套
有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套。可以在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典。
字典列表
字典alien_0 包含一个外星人的各种信息,但无法存储第二个外星人的信息。可以创建一个外星人列表,其中每个外星人都是一个字典,包含有关该外星人的信息。
#!/usr/bin/env python
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)
使用range()生成30个外星人
#!/usr/bin/env python
# 创建一个用于存储外星人的空列表
aliens = []
# 创建30哥绿色的外星人
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
# 显示前五个外星人
for alien in aliens[5]:
print(alien)
print("...")
# 显示创建了多少个外星人
print("Total number of aliens: " + str(len(aliens)))
1 C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/favorite_languages.py 2 {'color': 'green', 'points': 5} 3 {'color': 'yellow', 'points': 10} 4 {'color': 'red', 'points': 15}
这些外星人都具有相同的特征,但在Python看来,每个外星人都是独立的。
#!/usr/bin/env python
# 创建一个用于存储外星人的空列表
aliens = []
# 创建30哥绿色的外星人
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
# 显示前五个外星人
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
# 显示前五个外星人
for alien in aliens[0:5]:
print(alien)
print("...")
C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/favorite_languages.py {'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'} ...
在字典中存储列表
将列表存储在字典中。例如,如何描述顾客点的比萨呢?如果使用列表,只能存储要添加的比萨配料;但如果使用字典,就不仅在其中包含配料列表,还可以包含其他比萨的描述。下面的示例,存储比萨的两方面信息:外皮类型和配料列表。
# 存储所点比萨的信息
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)
C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/favorite_languages.py You ordered a thick-crust pizza with the following toppings: mushrooms extra cheese
每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表。下例中:在遍历字典的for循环中,需要再使用一个for循环来遍历与键相关联的值
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())
C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/favorite_languages.py 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
在字典中存储字典
字典中嵌套字典
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())
首先定义users字典,包含两个键用户名'aeinstein'和'mcurie';与每个键相关联的值都是一个字典,其中包含用户的名、姓和居住地。遍历字典users ,让Python依次将每个键存储在变量username中,并依次将与当前键相关联的变量user_info中。
在变量user_info包含用户信息字典,而该字典包含三个键:'first'、'last'、'location'。
C:\PyProjects>C:/Python37/python3.exe c:/PyProjects/favorite_languages.py
Username: aeinstein
Full name: Albert Einstein
Location: Princeton
Username: mcurie
Full name: Marie Curie
Location: Paris
请注意,表示每位用户的字典的结构都相同,虽然Python并没有这样的要求,但这使得嵌套的字典处理起来更容易。倘若表示每位用户的字典都包含不同的键,for循环内部的代码将更复杂。
浙公网安备 33010602011771号