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

如何对字典列表中相同key的value值求和合并?

实现字典列表中相同key的value值求和

实现思路

借助一个临时字典记录每个key对应的累计value值,遍历原列表完成累加后,再将临时字典转换为目标格式的字典列表。

代码实现

# 原字典列表
original_list = [{'key': '', 'value': 494}, {'key': 'cloud', 'value': 63}, {'key': 'cloud', 'value': 44}]

# 初始化临时字典用于累加value
sum_dict = {}
for item in original_list:
    current_key = item['key']
    current_value = item['value']
    # 存在对应key则累加value,不存在则初始化
    if current_key in sum_dict:
        sum_dict[current_key] += current_value
    else:
        sum_dict[current_key] = current_value

# 转换为目标格式的字典列表
result = [{'key': k, 'value': v} for k, v in sum_dict.items()]

print(result)

运行结果

[{'key': '', 'value': 494}, {'key': 'cloud', 'value': 107}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:57:19