Python 字典
在 Python 中,字典是 key: value 对的有序(Python > 3.7 起)集合。
来自 Python 3 文档
字典的主要操作是使用某个键存储一个值,以及给定一个键来提取该值。也可以使用 del 删除一个键:值对。
示例字典:
# 字典:键值对的集合
my_cat = {
'size': 'fat', # 键:'size', 值:'fat'
'color': 'gray', # 键:'color', 值:'gray'
'disposition': 'loud' # 键:'disposition', 值:'loud'
}
使用下标运算符 [] 设置键、值
# 使用下标运算符添加或更新字典条目
my_cat = {
'size': 'fat',
'color': 'gray',
'disposition': 'loud',
}
my_cat['age_years'] = 2 # 添加新的键值对
print(my_cat)
{'size': 'fat', 'color': 'gray', 'disposition': 'loud', 'age_years': 2}
使用下标运算符 [] 获取值
如果字典中不存在该键,则会引发 KeyError。
my_cat = {
'size': 'fat',
'color': 'gray',
'disposition': 'loud',
}
print(my_cat['size'])
fat
print(my_cat['eye_color'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'eye_color'
values()
values() 方法获取字典的值:
# 使用 .values() 方法迭代字典值
pet = {'color': 'red', 'age': 42}
for value in pet.values(): # 遍历所有值
print(value)
red
42
keys()
keys() 方法获取字典的键:
# 使用 .keys() 方法迭代字典键
pet = {'color': 'red', 'age': 42}
for key in pet.keys(): # 遍历所有键
print(key)
color
age
由于默认情况下您将遍历键,因此没有必要使用 .keys():
# 直接迭代字典会遍历键(默认行为)
pet = {'color': 'red', 'age': 42}
for key in pet: # 等同于 for key in pet.keys()
print(key)
color
age
items()
items() 方法获取字典的项,并将它们作为 元组 (Tuple) 返回:
pet = {'color': 'red', 'age': 42}
for item in pet.items():
print(item)
('color', 'red')
('age', 42)
使用 keys()、values() 和 items() 方法,for 循环可以分别迭代字典中的键、值或键值对。
# 使用 .items() 方法迭代键值对
pet = {'color': 'red', 'age': 42}
for key, value in pet.items(): # 将元组解包为键和值
print(f'Key: {key} Value: {value}')
Key: color Value: red
Key: age Value: 42
get()
get() 方法返回具有给定键的项的值。如果键不存在,它返回 None:
# .get() 方法:安全地检索值,如果键不存在则返回 None
wife = {'name': 'Rose', 'age': 33}
f'My wife name is {wife.get("name")}' # 返回 'Rose'
'My wife name is Rose'
f'She is {wife.get("age")} years old.'
'She is 33 years old.'
f'She is deeply in love with {wife.get("husband")}'
'She is deeply in love with None'
您也可以将默认的 None 值更改为您选择的任何值:
wife = {'name': 'Rose', 'age': 33}
f'She is deeply in love with {wife.get("husband", "lover")}'
'She is deeply in love with lover'
使用 setdefault() 添加项
可以通过这种方式向字典添加一个项:
wife = {'name': 'Rose', 'age': 33}
if 'has_hair' not in wife:
wife['has_hair'] = True
使用 setdefault 方法,我们可以使相同的代码更简洁:
wife = {'name': 'Rose', 'age': 33}
wife.setdefault('has_hair', True)
wife
{'name': 'Rose', 'age': 33, 'has_hair': True}
移除项
pop()
pop() 方法根据给定的键移除并返回一个项。
wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}
wife.pop('age')
33
wife
{'name': 'Rose', 'hair': 'brown'}
测验
登录后即可答题并追踪学习进度
当在字典上调用
pop() 时,它会做什么?A. 只移除键值对
B. 移除并返回指定键的值
C. 只返回值而不移除它
D. 移除字典中的所有项
popitem()
popitem() 方法移除字典中的最后一个项并返回它。
wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}
wife.popitem()
('hair', 'brown')
wife
{'name': 'Rose', 'age': 33}
del
del 方法根据给定的键移除一个项。
wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}
del wife['age']
wife
{'name': 'Rose', 'hair': 'brown'}
clear()
clear() 方法移除字典中的所有项。
wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}
wife.clear()
wife
{}
在字典中检查键
person = {'name': 'Rose', 'age': 33}
'name' in person.keys()
True
'height' in person.keys()
False
'skin' in person # 可以省略 keys()
False
在字典中检查值
person = {'name': 'Rose', 'age': 33}
'Rose' in person.values()
True
33 in person.values()
True
漂亮打印 (Pretty Printing)
import pprint
wife = {'name': 'Rose', 'age': 33, 'has_hair': True, 'hair_color': 'brown', 'height': 1.6, 'eye_color': 'brown'}
pprint.pprint(wife)
{'age': 33,
'eye_color': 'brown',
'hair_color': 'brown',
'has_hair': True,
'height': 1.6,
'name': 'Rose'}
合并两个字典
对于 Python 3.5+:
dict_a = {'a': 1, 'b': 2}
dict_b = {'b': 3, 'c': 4}
dict_c = {**dict_b, **dict_a}
dict_c
{'a': 1, 'b': 3, 'c': 4}
测验
登录后即可答题并追踪学习进度
当使用
{**dict_b, **dict_a} 合并两个字典时,如果两个字典具有相同的键,会发生什么?A.
dict_b 中的值会覆盖 dict_a 中的值B.
dict_a 中的值会覆盖 dict_b 中的值C. 两个值都会被保留在一个列表中
D. 引发错误