第六章: 字典(Dictionary)
文章目录
字典是 Python 提供的一种常用的数据结构,它用于存放具有映射关系的数据。
6.1 一个简单的字典
alien_0 = {'color':'green','points': 5}
print(alien_0['color'])
print(alien_0['points'])
green
5
6.2 使用字典
-
比如有份成绩表数据,语文:79,数学:80,英语:92,这组数据看上去像两个列表,但这两个列表的元素之间有一定的关联关系。如果单纯使用两个列表来保存这组数据,则无法记录两组数据之间的关联关系。
-
为了保存具有映射关系的数据,Python 提供了字典,字典相当于保存了两组数据(键值对,Key-Value Pair),其中一组数据是关键数据,被称为 key;另一组数据可通过 key 来访问,被称为 value。形象地看,字典中 key 和 value 的关联关系如图所示:

- 字典中的 key 是非常关键的数据,而且程序需要通过 key 来访问 value,因此字典中的 key 不允许重复
- 与key 关联的value 可以是数,字符串,列表,字典
- Python中,字典用放在{ }中的一系列键值对表示,key与value之间用:分隔,Key-Value Pair 之间用,分隔
- 字典——{ };列表——[ ];元组——( )
- 字典中可以包含任意多个键值对,最简单的字典只包含一个键值对
6.2.1 访问字典中的值
指定字典名(alien_0)+键(color)可获得值(green)
alien_0 = {'color':'green'}
print(alien_0['color'])
green
# 外星人被射杀后打印获得的分数
alien_0 = {'color':'green','points': 5}
new_points = alien_0['points']
print(f"You just earned {new_points} points!")
You just earned 5 points!
6.2.2 添加键值对
- 字典是一种动态结构,可随时添加键值对
- 指定字典名、用方括号括起的键和关联的值
alien_0 = {'color':'green','points': 5}
print(alien_0)
#新增外星人的x坐标和y坐标
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
注意:
- Python3.7中,字典中元素的排列顺序与定义时相同
- 将字典打印出来或遍历其元素,元素的排列顺序与添加顺序相同
6.2.3 创建空字典
- 使用字典来存储用户 提供的数据或者在编写能自动生成大量键值对的代码时,通常需定义一个空字典,然后再往空字典中添加键值对。
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
{'color': 'green', 'points': 5}
6.2.4 修改字典中的值
alien_0 = {'color': 'green', 'points': 5}
print (f"The alien is {alien_0['color']}")
alien_0['color'] = 'yellow'
print (f"The alien is {alien_0['color']}")
The alien is green
The alien is yellow
任务: 对一个能够以不同速度移动的外星人进行位置跟踪。首先存储该外星人的当前速度,并据此确定该外星人将向右移动多远
alien_0 = {'x_position': 0,
'y_position': 25,
'speed': 'medium'}
print(f"Original position: {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(f"New position: {alien_0['x_position']}")
Original position: 0
New position: 2
6.2.5 删除键值对——del
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
{'color': 'green', 'points': 5}
{'color': 'green'}
6.2.6 由类似对象组成的字典
- 字典可以存储一个对象的多种信息(外星人的各种信息)
- 字典也可以存储多个对象的同一种信息
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil':'python',
}
# 任务:打印sarah喜欢的编程语言
print(f"Sarah's favorite language is {favorite_languages['sarah'].title()}.")
Sarah's favorite language is C.
6.2.7 使用get来访问值
alien_0 = {'color': 'green', 'speed': 'slow'}
print(alien_0['points'])
- 如果指定的键不存在,但为了避免报错,可使用get()在指定键不存在时返回一个指定值
- get(key, value). key: 指定的key; value: 指定的key不存在时要反回的值(可选)
- dict[] 与dict.get() 的区别:如果指定的key有可能不存在,应考虑使用get().
alien_0 = {'color': 'green', 'speed': 'slow'}
point_value = alien_0.get('point', 'No point value assigned.')
print(point_value)
No point value assigned.
alien_0 = {'color': 'green', 'speed': 'slow'}
point_value = alien_0.get('point')
print(point_value)
None.
6.3 遍历字典
- 字典可能包括大量数据,因此需考虑遍历
- 可遍历字典所有的键值对,也可以仅遍历键或值
6.3.1 遍历所有键值对—— dict.items()
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
注意:
- 变量key, value 分别对应键和值,也可以用其它变量;
- dict.item(): 返回可遍历的(键, 值) 元组数组。
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil':'python',
}
for name, language in favorite_languages.items():
print(f"{name.title()}' favorite language is {language.title()}.")
Jen' favorite language is Python.
Sarah' favorite language is C.
Edward' favorite language is Ruby.
Phil' favorite language is Python.
6.3.2 遍历字典中所有键——dict.keys()
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil':'python',
}
for name in favorite_languages.keys():
print(name.title())
Jen
Sarah
Edward
Phil
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil':'python',
}
friends = ['sarah','phil']
for name in favorite_languages.keys():
print(f"Hi, {name.title()}.")
if name in friends:
language = favorite_languages[name].title()
print(f"\t{name.title()}, I see you love {language}!")
Hi, Jen.
Hi, Sarah.
Sarah, I see you love C!
Hi, Edward.
Hi, Phil.
Phil, I see you love Python!
6.3.3 按特定顺序遍历字典中所有的键
- 用sorted()获取按特定顺序排列的键列表的副本
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil':'python',
}
for name in sorted(favorite_languages.keys()):
print(f"{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.
6.3.4 遍历字典中所有值——dict.values()
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil':'python',
}
print("The following language have been mentioned:")
for language in favorite_languages.values():
print(language.title())
Python
C
Ruby
Python
- set():对包含重复元素的列表调用,可以找出列表中独一无二的元素并创建一个集合
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil':'python',
}
print("The following language have been mentioned:")
for language in set(favorite_languages.values()):
print(language.title())
The following language have been mentioned:
Python
C
Ruby
集合和字典:
- {}也可以创建集合 languages = {‘python’, ‘ruby’,‘python’,‘c’}
- 当{}中没有键值对时,定义的很可能是集合
6.4 嵌套(套娃)
- 字典中存储列表
- 列表中存储字典
- 字典中存储字典
- Python中几乎所有的数据类型,都可以存进字典里
6.4.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}
任务: 如何创建多个外星人
#创建一个用于存储外星人的空列表
aliens = []
#创建30个外星人
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("...")
# 显示创建了多少外星人
print(f"Total number of aliens: {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
任务: 修改前3个外星人的颜色,得分和速度
#创建一个用于存储外星人的空列表
aliens = []
#创建30个外星人
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'] = 'yallow'
alien['speed'] = 'medium'
alien['points'] = 10
#显示前5个外星人
for alien in aliens[:5]:
print(alien)
{'color': 'yallow', 'points': 10, 'speed': 'medium'}
{'color': 'yallow', 'points': 10, 'speed': 'medium'}
{'color': 'yallow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
6.4.2 字典中存储列表
任务: 存储顾客所点的披萨的信息
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
#概述所点的披萨
print(f"You order a {pizza['crust']}-crust pizza with the following toppings:")
for topping in pizza['toppings']:
print("\t" + topping)
You order a thick-crust pizza with the following toppings:
mushrooms
extra cheese
6.4.3 字典中存储字典
任务: 存储多个用户信息
- 在字典中用用户名作为key
- 将每位用户的信息存储为一个字典
- 将以上字典作为与key关联的value
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton'
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris'
},
}
for username, user_info in users.items():
print(f"\nUsername: {username}")
full_name = f"{user_info['first']} {user_info['last']}"
location = user_info['location']
print(f"\tFull name: {full_name.title()}")
print(f"\tLocation: {location.title()}")
Username: aeinstein
Full name: Albert Einstein
Location: Princeton
Username: mcurie
Full name: Marie Curie
Location: Paris
总结

本文介绍了Python字典的基本操作,包括创建、访问、修改、删除键值对,以及遍历字典的方法。通过示例展示了如何使用字典存储和处理数据,如外星人信息、成绩表和用户语言偏好。此外,还探讨了字典的嵌套使用,如字典列表和字典中存储字典。

2396

被折叠的 条评论
为什么被折叠?



