You need to enable JavaScript to run this app. Python如何对字典列表中相同公共key对应的数值进行累加求和
优惠活动
大模型
产品
解决方案
定价
更多

Python如何对字典列表中相同公共key对应的数值进行累加求和

字典列表重复taxType对应amount求和方案

实现逻辑

  • 初始化临时字典用于存储每个taxType对应的累计金额,以taxType取值为键,累计amount为值
  • 遍历原始字典列表,对同taxType的amount做累加计算
  • 将存储了累计结果的临时字典转换为要求的列表嵌套字典输出格式

示例代码

# 原始数据
tax = [{'taxType': 'T1', 'amount': 140},{'taxType': 'T1', 'amount': 10}]

# 累加计算
tax_counter = {}
for entry in tax:
    t_type = entry['taxType']
    tax_counter[t_type] = tax_counter.get(t_type, 0) + entry['amount']

# 转换为目标格式
tax = [{'taxType': tax_type, 'amount': total} for tax_type, total in tax_counter.items()]

运行验证

执行打印语句 print(tax),输出结果为:

[{'taxType': 'T1', 'amount': 150}]

该方案可自动适配多种不同taxType的重复合并场景,无需手动指定需要合并的taxType取值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 13:06:03