You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何对嵌套字典列表中相同键对应的数值进行求和

解法1:使用collections.defaultdict实现

可以嵌套两层defaultdict来累计数值,实现代码如下:

from collections import defaultdict

data = [
    {"2010" : {'A' : 2,'B' : 3,'C' : 5,}},    
    {"2011" : {'A' : 1,'B' : 2,}},
    {"2010" : {'A' : 1,'B' : 2,}}
]

res = defaultdict(lambda: defaultdict(int))
for item in data:
    for year, count_dict in item.items():
        for cate, num in count_dict.items():
            res[year][cate] += num

# 若需要最终结果为普通字典而非defaultdict,可加一步转换
res = {k: dict(v) for k, v in res.items()}

运行后得到的res和你期望的输出完全一致。

解法2:无依赖的原生Python实现

如果不想导入额外模块,也可以用字典的get方法做兼容处理:

res = {}
for item in data:
    for year, count_dict in item.items():
        if year not in res:
            res[year] = {}
        for cate, num in count_dict.items():
            res[year][cate] = res[year].get(cate, 0) + num

两种写法逻辑一致,都是遍历所有层级的键,对相同键的数值做累加,简洁易读。

内容的提问来源于stack exchange,提问作者Bob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 23:27:03