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

如何对Python列表中嵌套字典的特定键对应值求和(不使用pandas)

方案1:Python标准库实现(无额外依赖)

可以直接用collections模块下的工具完成统计,不需要安装任何第三方包:

方法1.1 使用Counter(最简洁标准库写法)

Counter原生支持相同键的数值累加,直接对所有年份统计字典求和即可:

from collections import Counter

main_list = [
    {"Afghanistan":{"1990":23000, "1991":29000, "1992":40000}},
    {"Armenia": {"1990":40000, "1991":32211, "1992":89999}}
]

# 提取所有年份字典转为Counter后累加
year_total = sum((Counter(next(iter(country.values()))) for country in main_list), Counter())
print(dict(year_total))

输出结果:{'1990': 63000, '1991': 61211, '1992': 129999}

方法1.2 使用defaultdict(可读性更高)

如果偏好更易理解的写法,可以用defaultdict实现:

from collections import defaultdict

year_total = defaultdict(int)
for country_dict in main_list:
    for year, val in next(iter(country_dict.values())).items():
        year_total[year] += val
print(dict(year_total))
方案2:第三方库极简实现(轻量无负担)

推荐使用轻量数据处理库toolz,比pandas体积小很多,专门做这类字典/序列的聚合操作,安装命令:pip install toolz
仅需一行代码即可完成统计:

from toolz.dicttoolz import merge_with

year_total = merge_with(sum, *(next(iter(item.values())) for item in main_list))
print(year_total)

merge_with会自动将所有传入字典的相同键值交给指定的聚合函数(这里是sum)计算,写法最简洁高效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:15:05