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

如何将字典列表转换为键一致、值为同键数值求和结果的字典

字典列表键值汇总实现方案

需求说明

对包含多个字典的列表进行汇总,规则如下:

  • 保留原列表中所有字典出现过的全部键
  • 每个键对应的值为列表中所有字典同键值的求和结果

示例参考

输入示例:
[{'Horror': 3, 'Romance': 3, 'Comedy': 1, 'Action': 3, 'History': 2}, {'Action': 0, 'Horror': 0, 'Romance': 0, 'Comedy': 0, 'History': 0, 'Adventure': 0}]

输出示例:
{'Horror': 3, 'Romance': 3, 'Comedy': 1, 'Action': 3, 'History': 2, 'Adventure': 0}

Python 实现代码

方案1:依赖collections.Counter实现(代码最简)

利用Counter的累加特性直接完成汇总:

from collections import Counter

def sum_dict_list(dict_list):
    res = Counter()
    for item in dict_list:
        res.update(item)
    return dict(res)

# 调用测试
test_input = [{'Horror': 3, 'Romance': 3, 'Comedy': 1, 'Action': 3, 'History': 2}, {'Action': 0, 'Horror': 0, 'Romance': 0, 'Comedy': 0, 'History': 0, 'Adventure': 0}]
print(sum_dict_list(test_input))

方案2:原生Python实现(无额外依赖)

手动遍历统计,无需导入任何模块:

def sum_dict_list(dict_list):
    # 收集所有出现过的键
    all_keys = set()
    for item in dict_list:
        all_keys.update(item.keys())
    # 逐个键求和
    return {key: sum(item.get(key, 0) for item in dict_list) for key in all_keys}

# 调用测试
test_input = [{'Horror': 3, 'Romance': 3, 'Comedy': 1, 'Action': 3, 'History': 2}, {'Action': 0, 'Horror': 0, 'Romance': 0, 'Comedy': 0, 'History': 0, 'Adventure': 0}]
print(sum_dict_list(test_input))

内容的提问来源于stack exchange,提问作者Nastaran.hh92

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 23:36:10