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

如何在Python中按字典值对列表字典分组合并并求和

合并相同日期的发票数据

需求说明

现有发票数据如下:

from datetime import date

invoices = [
    {'name': 'INV/2021/0913', 'invoice_date': date(2021, 3, 12), 'qty_total': 5.0}, 
    {'name': 'INV/2021/0965', 'invoice_date': date(2021, 3, 14), 'qty_total': 6.0}, 
    {'name': 'INV/2021/0966', 'invoice_date': date(2021, 3, 14), 'qty_total': 7.0}, 
    {'name': 'INV/2021/0967', 'invoice_date': date(2021, 3, 14), 'qty_total': 3.0}, 
    {'name': 'INV/2021/0992', 'invoice_date': date(2021, 3, 15), 'qty_total': 4.0}
]

需要实现:

  • 将具有相同invoice_date的条目合并,对qty_total求和
  • 合并后的条目name设为空字符串;单个日期的条目保留原name

预期输出:

[
    {'name': 'INV/2021/0913', 'invoice_date': date(2021, 3, 12), 'qty_total': 5.0}, 
    {'name': '', 'invoice_date': date(2021, 3, 14), 'qty_total': 16.0}, 
    {'name': 'INV/2021/0992', 'invoice_date': date(2021, 3, 15), 'qty_total': 4.0}
]

实现方案

代码实现

from datetime import date
from collections import defaultdict

# 原始数据
invoices = [
    {'name': 'INV/2021/0913', 'invoice_date': date(2021, 3, 12), 'qty_total': 5.0}, 
    {'name': 'INV/2021/0965', 'invoice_date': date(2021, 3, 14), 'qty_total': 6.0}, 
    {'name': 'INV/2021/0966', 'invoice_date': date(2021, 3, 14), 'qty_total': 7.0}, 
    {'name': 'INV/2021/0967', 'invoice_date': date(2021, 3, 14), 'qty_total': 3.0}, 
    {'name': 'INV/2021/0992', 'invoice_date': date(2021, 3, 15), 'qty_total': 4.0}
]

# 按日期分组统计
date_groups = defaultdict(lambda: {'entry_count': 0, 'total_qty': 0.0, 'invoice_name': ''})
for inv in invoices:
    date_key = inv['invoice_date']
    group = date_groups[date_key]
    group['total_qty'] += inv['qty_total']
    group['entry_count'] += 1
    
    # 单个条目保留原名称,多个条目清空名称
    if group['entry_count'] == 1:
        group['invoice_name'] = inv['name']
    else:
        group['invoice_name'] = ''

# 转换为目标格式并按日期排序
merged_invoices = [
    {
        'name': group['invoice_name'],
        'invoice_date': date_key,
        'qty_total': group['total_qty']
    }
    for date_key, group in sorted(date_groups.items())
]

# 打印结果
for item in merged_invoices:
    print(item)

逻辑说明

  1. 分组统计:使用defaultdict创建分组容器,每个分组记录该日期的条目数、总数量和发票名称;
  2. 遍历处理:逐个遍历原始发票数据,累加对应日期的总数量,同时根据条目数决定是否保留原名称;
  3. 格式转换:将分组后的结果转换为目标字典格式,并按日期排序以保证输出顺序与原始数据一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 17:50:42