CodeWalk

defaultdict 的用法

作者:Yahuda · 2026-05-30 12:55

collections.defaultdict 的作用是什么?与普通 dict 相比有什么优势?请给出代码示例。

回答

Yahuda

defaultdict 为不存在的键提供默认值,避免 KeyError

from collections import defaultdict

# 普通 dict 需要先检查
words = ['apple', 'banana', 'apple', 'cherry']
count = {}
for w in words:
    if w not in count:
        count[w] = 0
    count[w] += 1

# defaultdict
count = defaultdict(int)  # 默认值 0
for w in words:
    count[w] += 1

# 分组
groups = defaultdict(list)
for w in words:
    groups[w[0]].append(w)
# {'a': ['apple', 'apple'], 'b': ['banana'], 'c': ['cherry']}

可传入任何可调用对象:int(0)、list([])、set(set())、lambda: 'N/A'