Python 中的字典允许程序员将相关的信息片段联系起来。字典中的每条信息都以键值对的形式存储。这与其它流行的编程语言中的关联数组相似。要访问一个字典中的值,你要提供相关的键。你可以在访问所有的值、键或整个键值对时在字典上循环。在本教程中,我们将看看如何创建一个字典,如何获得一个键的值,如何把一个字典放在一个列表中,如何添加新的键值对,如何修改值,等等。

如何创建一个字典
要在 Python 中创建一个字典,你可以使用大括号 { }.在大括号内,一个冒号 **:**用来关联各种键值对。
制作一个字典
player_0 = {'level': 'novice', 'points': 7}

获取一个键的值
有几种方法可以使用存储在字典中的值。要访问与一个特定键相关的值,可以指定字典的名称,然后把键放在一组方括号内 [ ].如果你试图访问一个不存在的键,Python 将输出一个 KeyError 消息。还有一个 **get()**方法,如果键不存在,它返回 **None**而不是一个错误,如果键不存在的话。也可以指定一个默认值,在键不在字典中时使用。
访问与一个给定键相关的值
player_0 = {'level': 'novice', 'points': 7}
print(player_0['level'])
print(player_0['points'])

使用 **get()**方法来访问一个值
player_0 = {'level': 'novice'}
player_level = player_0.get('level')
player_points = player_0.get('points', 0)
print(player_level)
print(player_points)

列表中的字典
可以定义一个 dictionary,然后将其存储在一个 list 中。这就是所谓的嵌套。
在一个列表中存储字典
# Start with an empty list.
profiles = []
# Make a new profile, and add them to the list.
new_profile = {
'last': 'Diaz',
'first': 'Guillermo',
'profilename': 'gDiaz',
}
profiles.append(new_profile)
# Make another new profile, and add them as well.
new_profile = {
'last': 'Rezende',
'first': 'Pedro',
'profilename': 'pRezende',
}
profiles.append(new_profile)
# Show all information about each profile.
for profile_dict in profiles:
for k, v in profile_dict.items():
print(f"{k}: {v}")
print("n")
last: Diaz
first: Guillermo
profilename: gDiaz
last: Rezende
first: Pedro
profilename: pRezende

定义一个不使用字典的列表 append()
# Define a list of profiles, where each profile
# is represented by a dictionary.
profiles = [
{
'last': 'Diaz',
'first': 'Guillermo',
'profilename': 'eDiaz',
},
{
'last': 'Rezende',
'first': 'Pedro',
'profilename': 'mRezende',
},
]
# Show all information about each profile.
for profile_dict in profiles:
for k, v in profile_dict.items():
print(f"{k}: {v}")
print("n")
last: Diaz
first: Guillermo
profilename: eDiaz
last: Rezende
first: Pedro
profilename: mRezende

添加新的键值对
你可以在 dictionary 中存储多少个键值对的唯一限制是由 Python 程序所运行的机器上的内存量决定的。当然,你很可能永远都不需要那么多的键值对,但是如果你想的话,知道你可以有几百万个键值对是件好事。你可以在现有的 dictionary 中增加一个新的键值对,方法是在方括号中给出 dictionary 的名字和新的键。然后,将新的值设置到该表达式中。你可以从一个空的 dictionary 开始,根据需要添加键值对。
添加一个键值对
player_0 = {'level': 'novice', 'points': 7}
player_0['x'] = 0
player_0['y'] = 25
player_0['speed'] = 1.5
上面的代码也可以像这样写成一个字典字面。
player_0 = {'level': 'novice', 'points': 7, 'x': 0, 'y': 25, 'speed': 1.5}
添加到一个空的 dictionary 中
player_0 = {}
player_0['level'] = 'novice'
player_0['points'] = 7
如何修改值
由于 dictionary 是可变的,你可以改变与 dictionary 中任何键相关的值。提供 dictionary 的名称,
,把键放在方括号里,然后提供该键的新值,以修改原来的值。
修改 dictionary 中的值
player_0 = {'level': 'novice', 'points': 7}
print(player_0)
# Change the player's level and point value.
player_0['level'] = 'intermediate'
player_0['points'] = 10
print(player_0)
{'level': 'novice', 'points': 7}
{'level': 'intermediate', 'points': 10}

删除键值对
要从一个 dictionary 中删除一个 key-value 对,可以使用 **del**关键字。使用 del 关键字,然后提供 dictionary 名称,后面是方括号中的 key。这将从 dictionary 中删除这个键和它的相关值。
删除一个键值对
player_0 = {'level': 'novice', 'points': 7}
print(player_0)
del player_0['points']
print(player_0)
{'level': 'novice', 'points': 7}
{'level': 'novice'}
在 dictionary 中存储一个列表允许你为每个键关联一个以上的值。
在 dictionary 中存储列表
# Store multiple games for each person.
fav_games = {
'Pedro': ['Outer Wilds', 'Disco Elysium'],
'Sean': ['Baba Is You'],
'Daniel': ['Sekiro', 'Star Wars Jedi'],
'Guillermo': ['Control', 'Dragon Quest Builders 2'],
}
# Show all responses for each person.
for name, games in fav_games.items():
print(f"{name}: ")
for game in games:
print(f"- {game}")
Pedro:
- Outer Wilds
- Disco Elysium
Sean:
- Baba Is You
Daniel:
- Sekiro
- Star Wars Jedi
Guillermo:
- Control
- Dragon Quest Builders 2

字典的字典
你可以把一个 dictionary 存储在另一个 dictionary 内。在这种情况下,与一个键关联的每个值本身就是一个字典。
在一个字典中存储字典
profiles = {
'smcloughlin': {
'first': 'Sean',
'last': 'McLoughlin',
'gender': 'male',
},
'prezende': {
'first': 'Pedro',
'last': 'Rezende',
'gender': 'male',
},
}
for profilename, profile_dict in profiles.items():
print("nUsername: " + profilename)
full_name = profile_dict['first'] + " "
full_name += profile_dict['last']
gender = profile_dict['gender']
print(f"tFull name: {full_name.title()}")
print(f"tgender: {gender.title()}")
Username: smcloughlin
Full name: Sean Mcloughlin
gender: Male
Username: prezende
Full name: Pedro Rezende
gender: Male

避免过多的嵌套
嵌套在某些情况下可能非常有用。缺点是这可能会使代码比理想的情况更复杂。如果你发现自己嵌套的项目比这里的例子更深,那么可能有更好的方法来管理你的数据。一个选择是使用类来处理数据管理。
循环浏览一个 dictionary
有三种不同的方法来循环浏览一个 dictionary。第一种是循环浏览字典中所有的值。其次是在所有的键上循环。最后一种是在所有的键值对上循环。不同的问题需要不同的方法。当你把键值对添加到 dictionary 中时,它将跟踪它们被添加的顺序。要以不同的顺序处理数据,你可以在循环中对键进行排序。
循环处理所有键值对
# Store people's favorite games.
fav_games = {
'George': 'Crash Bandicoot',
'Alex': 'Super Smash Bros',
'Sarah': 'Legend Of Zelda',
'Allison': 'Pong',
}

# Show each person's favorite game.
for name, game in fav_games.items():
print(f"{name}: {game}")
George: Crash Bandicoot
Alex: Super Smash Bros
Sarah: Legend Of Zelda
Allison: Pong
循环处理所有的键
# Show everyone who's taken the survey.
for name in fav_games.keys():
print(name)
George
Alex
Sarah
Allison
循环处理所有的值
# Show all the games that have been chosen.
for game in fav_games.values():
print(game)
以相反的顺序循环处理所有的键
# Show each person's favorite game,
# in reverse order by the person's name.
for name in sorted(fav_games.keys(), reverse=True):
print(f"{name}: {fav_games[name]}")
Sarah: Legend Of Zelda
George: Crash Bandicoot
Allison: Pong
Alex: Super Smash Bros
检查字典的长度
你可以通过使用函数找到字典中键值对的数量。 **len()**函数。
确定一个字典的长度
num_responses = len(fav_games)
print(num_responses)
4
字典的理解力
就像列表有理解的功能一样,字典也有理解的功能。理解力只是创建字典的一种紧凑方式。要制作一个字典的理解力,为你想制作的键值对定义一个表达式。然后写一个 for 循环来生成将输入这个表达式的值。zip() 函数将一个列表中的每个项目与第二个列表中的每个项目相匹配。它可以用来从两个列表中创建一个 dictionary。
使用一个循环来创建一个 dictionary
cubes = {}
for x in range(5):
cubes[x] = x ** 3

使用一个字典的理解力
cubes = {x: x ** 3 for x in range(5)}

使用 zip() 制作一个字典
veggies = ['pepper', 'broccoli', 'spinach', 'potato']
fruits = ['apple', 'orange', 'peach', 'plum']
combos = {key: key_2 for key, key_2 in zip(veggies, fruits)}

创建数以千计的字典
要一次创建大量的 dictionary,可以像这样使用一个循环。
players = []
# Make a thousand novice players, worth 3 points
# each. Have them all start in one row.
for player_num in range(1000):
new_player = {}
new_player['level'] = 'novice'
new_player['points'] = 3
new_player['x'] = 20 * player_num
new_player['y'] = 0
players.append(new_player)
# Show the list contains a thousand players.
num_players = len(players)
print("Number of players created:")
print(num_players)
Number of players created:
1000
Python中的字典摘要
Python 的 dictionary 类型是一个散列的键值结构。这与其他语言如 PHP 和 JavaScript 中的关联数组相类似。一个 dictionary 是用大括号创建的,其中有一个开口大括号和一个闭口大括号。大括号内是键值对。每个键值对的左边是一个键,右边是一个值,它们之间用冒号分开。在结构集内,键值对本身是由逗号隔开的。你也可以用 dictionary 构造函数和关键字参数来创建 dictionary。键值和值可以是任何类型。键值必须是不可变的。字符串和数字总是可以成为键。items() 方法返回一个键值对的视图。keys() 方法返回 dictionary key 的视图,values() 方法只给我们一个值的列表。一个 dictionary 是由它的键来索引的,所以你可以很容易地挑选一个特定的元素。如果你试图访问一个不存在的键,你会得到一个键错误异常。另一方面,当你不知道键是否存在时,你可以使用 get() 方法来返回一个值。Python 的字典类型既简单又有用,你会在常见的 Python 项目的代码中看到很多它的例子。