如何在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)
逻辑说明
- 分组统计:使用
defaultdict创建分组容器,每个分组记录该日期的条目数、总数量和发票名称; - 遍历处理:逐个遍历原始发票数据,累加对应日期的总数量,同时根据条目数决定是否保留原名称;
- 格式转换:将分组后的结果转换为目标字典格式,并按日期排序以保证输出顺序与原始数据一致。
内容的提问来源于stack exchange,提问作者Khaalidi
相关产品推荐
相关产品推荐

