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

如何基于两个字典列表创建新列表,合并同month键的amount值

按month键汇总两个字典列表的amount值

我有两个字典列表:

list1 = [{"month": "Jan", "amount":1}, {"month": "Feb", "amount":4}]
list2 = [{"month": "Jan", "amount":2}, {"month": "Feb", "amount":4}]

需要创建一个新的字典列表,保留相同的键,将拥有相同"month"键的字典的"amount"值相加,目标结果如下:

target = [{"month": "Jan", "amount":3}, {"month": "Feb", "amount": 8}]

基础解决方法

先用普通字典按month累计amount,再转换为目标列表格式:

# 合并两个输入列表
combined_list = list1 + list2

# 初始化临时字典,存储每个月份的总金额
monthly_total = {}
for entry in combined_list:
    current_month = entry["month"]
    current_amount = entry["amount"]
    if current_month in monthly_total:
        monthly_total[current_month] += current_amount
    else:
        monthly_total[current_month] = current_amount

# 将临时字典转换为目标格式的列表
target_list = [{"month": month, "amount": total} for month, total in monthly_total.items()]

print(target_list)
# 输出结果: [{'month': 'Jan', 'amount': 3}, {'month': 'Feb', 'amount': 8}]

简洁写法(利用collections.defaultdict)

借助collections模块的defaultdict可以简化判断逻辑,让代码更紧凑:

from collections import defaultdict

combined_list = list1 + list2
monthly_total = defaultdict(int)

for entry in combined_list:
    monthly_total[entry["month"]] += entry["amount"]

target_list = [{"month": month, "amount": total} for month, total in monthly_total.items()]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 16:12:37