
本文介绍在 Python 中将多个字典按相同键进行数值累加的简洁、Pythonic 方法,重点推荐使用 collections.Counter,避免手动循环,兼顾可读性与性能。
本文介绍在 python 中将多个字典按相同键进行数值累加的简洁、pythonic 方法,重点推荐使用 `collections.counter`,避免手动循环,兼顾可读性与性能。
在数据处理中,常需对一组结构相似的字典(如统计结果、特征向量)按键聚合数值——例如将 {1: 1.1, 2: 2.2} 和 {1: 3.3, 4: 5.5} 合并为 {1: 4.4, 2: 2.2, 4: 5.5}。此时,简单拼接(如 dict(d1.items() + d2.items()))或解包({**d1, **d2})会导致后出现的键值覆盖前值,无法实现求和。
最优雅的解决方案是借助 collections.Counter:它专为计数设计,其 + 运算符天然支持同键数值相加,且能无缝兼容浮点数、整数等数值类型。
✅ 基础用法(两个字典):
from collections import Counter
d1 = {1: 1.1, 2: 2.2}
d2 = {1: 3.3, 4: 5.5}
result = dict(Counter(d1) + Counter(d2))
print(result) # {1: 4.4, 2: 2.2, 4: 5.5}
✅ 扩展用法(任意数量字典,推荐):
当输入为字典列表(如 dicts = [d1, d2, d3, ...])时,可结合 map 与 sum 实现一行式聚合:
from collections import Counter
dicts = [{1: 1.1, 2: 2.2}, {1: 3.3, 4: 5.5}, {2: 0.8, 4: -1.0}]
final_dict = dict(sum(map(Counter, dicts), Counter()))
print(final_dict) # {1: 4.4, 2: 3.0, 4: 4.5}
? 注意:
sum(..., Counter())中的Counter()是起始值(即start参数),确保空列表输入时返回空字典{},避免TypeError。
⚠️ 使用限制与注意事项:
-
Counter默认将非数值值(如字符串、None)转为0或引发TypeError,仅适用于所有值均为数字类型(int/float/Decimal等)的场景; - 若字典含非数值值,或需自定义聚合逻辑(如取最大值、拼接字符串),应改用
defaultdict或itertools.groupby+ 手动聚合; - 性能上,
Counter方案时间复杂度为 O(N)(N 为所有键值对总数),与手动循环相当,但代码更简洁、语义更清晰。
综上,Counter 是 Python 标准库中为“键值累加”量身定制的工具——无需第三方依赖,语法简洁,语义明确,是真正 Pythonic 的首选方案。










