如何对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
相关产品推荐
相关产品推荐

