defaultdict
会为每个新键自动提供一个默认值,而普通字典没有这个功能。
defaultdict(float) 会自动为每个新键提供默认值 0.0(因为 float() 默认返回 0.0)。这在需要频繁累加或计数时非常方便,因为不需要每次先检查键是否存在。
示例对比
普通字典:
votes = {}
if 'example_key' in votes:
votes['example_key'] += 1
else:
votes['example_key'] = 1
defaultdict(float):
from collections import defaultdict
votes = defaultdict(float)
votes['example_key'] += 1 # 自动初始化 'example_key' 为 0.0,然后加 1