在 Python 中,collections.defaultdict
是一个非常有用的数据结构,可以为字典提供默认值。嵌套的 defaultdict 则允许我们方便地构建多级(多层)结构,而无需手动检查键是否存在。
1. 基础语法:defaultdict
from collections import defaultdict
d = defaultdict(list)
d['a'].append(1)
print(d) # defaultdict(<class 'list'>, {'a': [1]})
你不需要检查 'a'
是否存在,defaultdict
会自动初始化为一个空的 list
。
2. 嵌套 defaultdict
常见的 二维嵌套结构:
from collections import defaultdict
nested_dict = defaultdict(lambda: defaultdict(list))
nested_dict['1abc']['A__H1'].append('file1.pkl')
nested_dict['1abc']['A__H1'].append('file2.pkl')
nested_dict['2xyz']['B__L3'].append('file3.pkl')
print(nested_dict)
创建了一个外层 defaultdict
,其默认值是一个内层 defaultdict
,内层 defaultdict
的默认值为一个空列表。
常见用法示例
✅ 1. 构建多层结构(类似 JSON):
from collections import defaultdict
# 三层嵌套
tree = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))
tree['human']['brain']['neurons'] = 100_000_000_000
tree['human']['heart']['beats_per_min'] = 72
print(tree['human']['brain']['neurons']) # 100000000000
2. 统计词频(按文档和单词):
docs = {
"doc1": "hello world hello",
"doc2": "hello ai model",
}
word_counts = defaultdict(lambda: defaultdict(int))
for doc_id, text in docs.items():
for word in text.split():
word_counts[doc_id][word] += 1
print(word_counts)
# defaultdict(<function ...>, {
# 'doc1': defaultdict(<class 'int'>, {'hello': 2, 'world': 1}),
# 'doc2': defaultdict(<class 'int'>, {'hello': 1, 'ai': 1, 'model': 1})
# })
注意事项
defaultdict
会在访问不存在的键时自动创建新元素,有时可能会误操作(比如意外创建多余的键)。可以使用
dict(nested_dict)
或json.dumps(nested_dict)
将其转为普通结构,但需要先处理defaultdict
。