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

如何在Python中按月份汇总字典列表的金额?

问题描述

我有一组由字典组成的列表(注:原代码中的字典存在重复键,应为列表结构):

[
{"account": "x*", 'amount': 300, 'day': 3, 'month': 'June'},
{"account": "y*", 'amount': 550, 'day': 9, 'month': 'May'},
{"account": 'z*', 'amount': -200, 'day': 21, 'month': 'June'},
{"account" : "g", "amount" : 80, "day" : 10, "month" : "May"}
]

请问如何分别计算五月(May)和六月(June)的总金额?我尝试了以下代码,但无法实现需求:

dictionary= sum(d["amount"] for d in my_dict)
解决方案

方法1:分月份直接求和

针对目标月份筛选列表中的字典,再对amount字段求和:

# 先定义你的交易列表
transactions = [
    {"account": "x*", 'amount': 300, 'day': 3, 'month': 'June'},
    {"account": "y*", 'amount': 550, 'day': 9, 'month': 'May'},
    {"account": 'z*', 'amount': -200, 'day': 21, 'month': 'June'},
    {"account" : "g", "amount" : 80, "day" : 10, "month" : "May"}
]

# 计算五月总额
may_total = sum(d["amount"] for d in transactions if d["month"] == "May")
# 计算六月总额
june_total = sum(d["amount"] for d in transactions if d["month"] == "June")

print(f"五月总金额:{may_total}")  # 输出:630
print(f"六月总金额:{june_total}")  # 输出:100

方法2:通用型月份统计(支持多月份)

如果后续需要统计更多月份,用字典累计更高效:

monthly_totals = {}
for trans in transactions:
    month = trans["month"]
    # 累加金额,没有该月份则初始化为0再加当前金额
    monthly_totals[month] = monthly_totals.get(month, 0) + trans["amount"]

print(monthly_totals)  # 输出:{'June': 100, 'May': 630}
print(f"五月总金额:{monthly_totals['May']}")
print(f"六月总金额:{monthly_totals['June']}")

原代码问题说明

你之前的代码没有添加月份过滤条件,直接对所有交易的amount求和,得到的是所有月份的总金额,而非分月份的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 05:10:49