赞
踩
在本章中,你将学习能够将相关信息关联起来的Python字典。你将学习如何访问和修改字典中的信息。鉴于字典可存储的信息量几乎不受限制,因此我们会演示如何遍历字典中的数据。另外,你还将学习存储字典的列表、存储列表的字典和存储字典的字典。
- alien_0 = {'color': 'green', 'points': 5}
- print(alien_0['color'])
- print(alien_0['points'])
'运行
- green
- 5
alien_0 = {'color': 'green'}
'运行
- alien_0 = {'color': 'green'}
- print(alien_0['color'])
'运行
- alien_0 = {'color': 'green', 'points': 5}
- new_points = alien_0['points']
- print("You just earned " + str(new_points) + " points!")
'运行
- alien_0 = {'color': 'green', 'points': 5}
- print(alien_0)
- alien_0['x_position'] = 0
- alien_0['y_position'] = 25
- print(alien_0)
'运行
我们首先定义了前面一直在使用的字典,然后打印这个字典,以显示其信息快照。在❶处,我们在这个字典中新增了一个键—值对,其中的键为'x_position' ,而值为0 。在❷处,我们重复这样的操作,但使用的键为'y_position' 。打印修改后的字典时,将看到这两个新增的键—值对:
- {'color': 'green', 'points': 5}
- {'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
'运行
这个字典的最终版本包含四个键-值对,其中原来的两个指定外星人的颜色和点数,而新增的两个指定位置。注意,键-值对的排列顺序与添加顺序不同。Python不关心键—值对的添加顺序,而只关心键和值之间的关联关系。
- alien_0 = {}
- alien_0['color'] = 'green'
- alien_0['points'] = 5
- print(alien_0)
'运行
这里首先定义了空字典alien_0 ,再在其中添加颜色和点数,得到前述示例一直在使用的字典:
- 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.
- alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
- print("Original x-position: " + str(alien_0['x_position']))
- # 向右移动外星人
- # 据外星人当前速度决定将其移动多远
- if alien_0['speed'] == 'slow':
- x_increment = 1
- elif alien_0['speed'] == 'medium':
- x_increment = 2
- else:
- # 这个外星人的速度一定很快
- x_increment = 3
- # 新位置等于老位置加上增量
- alien_0['x_position'] = alien_0['x_position'] + x_increment
- print("New x-position: " + str(alien_0['x_position']))
'运行
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
- alien_0 = {'color': 'green', 'points': 5}
- print(alien_0)
- del alien_0['points']
- print(alien_0)
'运行
alien_0 = {'color': 'green', 'points': 5}
- favorite_languages = {
- 'jen': 'python',
- 'sarah': 'c',
- 'edward': 'ruby',
- 'phil': 'python',
- }
'运行
正如你看到的,我们将一个较大的字典放在了多行中。其中每个键都是一个被调查者的名字,而每个值都是被调查者喜欢的语言。
确定需要使用多行来定义字典时,在输入左花括号后按回车键,再在下一行缩进四个空格(可用Tab键),指定第一个键—值对,并在它后面加上一个逗号。此后你再次按回车键时,文本编辑器将自动缩进后续键—值对,且缩进量与第一个键—值对相同。
- favorite_languages = {
- 'jen': 'python',
- 'sarah': 'c',
- 'edward': 'ruby',
- 'phil': 'python',
- }
- print("Sarah's favorite language is " +
- favorite_languages['sarah'].title() +
- ".")
'运行
favorite_languages = {
'jen': 'python',
- user_0 = {
- 'username': 'efermi',
- 'first': 'enrico',
- 'last': 'fermi',
- }
- for key, value in user_0.items():
- print("\nKey: " + key)
- print("Value: " + value)
'运行
user_0 = { 'username': 'efermi',
- Key: username
- Value: efermi
-
- Key: first
- Value: enrico
-
- Key: last
- Value: fermi
- favorite_languages = {
- 'jen': 'python',
- 'sarah': 'c',
- 'edward': 'ruby',
- 'phil': 'python',
- }
- print("Sarah's favorite language is " +
- favorite_languages['sarah'].title() +
- ".")
-
- for name, language in favorite_languages.items():
- print(name.title() + "'s favorite language is " +
- language.title() + ".")
'运行
favorite_languages = {
- Sarah's favorite language is C.
- Jen's favorite language is Python.
- Sarah's favorite language is C.
- Edward's favorite language is Ruby.
- Phil's favorite language is 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():
- 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() + "!")
'运行
- Jen
- Sarah
- Hi Sarah, I see your favorite language is C!
- Edward
- Phil
- Hi Phil, I see your favorite language is Python!
- for name in sorted(favorite_languages.keys()):
- print(name.title() + ", thank you for taking the poll.")
- Edward, 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.
- print("The following languages have been mentioned:")
- for language in favorite_languages.values():
- print(language.title())
- The following languages have been mentioned:
- Python
- C
- Ruby
- Python
- favorite_languages2 = {
- 'jen': 'python',
- 'sarah': 'c',
- 'edward': 'ruby',
- 'phil': 'python',
- }
-
- print("The following languages have been mentioned:")
- for language in set(favorite_languages2.values()):
- print(language.title())
'运行
- The following languages have been mentioned:
- Ruby
- Python
- C
- 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}
'运行
- # 创建一个用于存储外星人的空列表
- 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)))
'运行
- {'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'}
- ...
- Total number of aliens: 30
这些外星人都具有相同的特征,但在
Python
看来,每个外星人都是独立的,这让我们能够独立地修改每个外星人。在什么情况下需要处理成群结队的外星人呢?想象一下,可能随着游戏的进行,有些外星人会变色且移动速度会加快。必要时,我们可以使用
for
循环和
if
语句来修改某些外星
- # 创建一个用于存储外星人的空列表
- aliens = []
- # 创建30个绿色的外星人
- for alien_number in range (0,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("...")
'运行
aliens = []
- {'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'}
- ...
'运行
你可以进一步扩展这个循环,在其中添加一个
elif
代码块,将黄色外星人改为移动速度快且值
15
个点的红色外星人,如下所示(这里只列出了循环,而没有列出整个程序):
- for alien in aliens[0:5]:
- 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
-
- for alien in aliens[0:5]:
- print(alien)
- {'color': 'red', 'points': 15, 'speed': 'fast'}
- {'color': 'red', 'points': 15, 'speed': 'fast'}
- {'color': 'red', 'points': 15, 'speed': 'fast'}
- {'color': 'yellow', 'points': 10, 'speed': 'medium'}
- {'color': 'yellow', 'points': 10, 'speed': 'medium'}
'运行
- # 存储所点比萨的信息
- 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())
'运行
❶ favorite_languages = {
- 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
- favorite_languages = {
- 'jen': ['python', 'ruby'],
- 'sarah': ['c'],
- 'edward': ['ruby', 'go'],
- 'phil': ['python', 'haskell'],
- }
-
- for name, languages in favorite_languages.items():
- if len(languages) == 1:
- print("\n" + name.title() + "'s favorite languages is:")
- for language in languages:
- print("\t" + language.title())
- else:
- 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 is:
- 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())
'运行
❶ for username, user_info in users.items():
- Username: aeinstein
- Full name: Albert Einstein
- Location: Princeton
-
- Username: mcurie
- Full name: Marie Curie
- Location: Paris
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。