1、遍历字典
遍历字典中的键和值
# 遍历字典中的键和值
for key, value in dict_a.items():
print(f"键: {key}, 值: {value}")
解释:使用 items() 方法可以同时获取字典中的键和值,这样可以方便地进行处理。
2、字典的默认值
使用 defaultdict 可以设置字典的默认值,从而避免键不存在时引发错误。
from collections import defaultdict
# 创建一个 defaultdict,默认值为0
scoreboard = defaultdict(int)
# 添加分数
scoreboard['Alice'] += 10
scoreboard['Bob'] += 5
print(scoreboard) # 输出: defaultdict(<class 'int'>, {'Alice': 10, 'Bob': 5})
解释:在这个例子中,defaultdict 使得我们在访问不存在的键时不会出现错误,而是返回默认值(这里是 0)。