You need to enable JavaScript to run this app. 如何聚合字典键值并将嵌套字典数据导出为CSV文件
优惠活动
大模型
产品
解决方案
定价
更多

如何聚合字典键值并将嵌套字典数据导出为CSV文件

账单字典转换为目标格式CSV的实现方案

整体流程拆为三个核心环节,不需要额外安装第三方依赖,用Python标准库即可完成:

1. 提取基础维度

  • 从原始字典f中提取所有顶层账单编号,作为CSV里除Item、Total列之外的列名,直接取字典键值即可保留原始账单顺序
  • 遍历所有账单下的商品明细,提取所有不重复的商品名称,作为CSV第一列的取值范围

2. 构建交叉统计矩阵

用嵌套的默认值容器做累加统计,逻辑为:

  • 以商品名称为第一层键,账单编号为第二层键,初始累计值为0
  • 逐行遍历所有明细条目,把对应商品、对应账单的采购数量累加到统计值中
  • 所有没有被明细命中的「商品-账单」组合,默认保留0值

3. 写入目标CSV

  • 按固定顺序组装表头:Item + 所有账单编号 + Total
  • 逐商品行取对应账单的累计值,缺失值补0,最后计算该商品的全局数量总和作为Total列值
  • 把原始的浮点型采购数量转换为整数格式写入,匹配示例的输出样式

完整可运行代码

from collections import defaultdict
import csv

# 原始账单字典
f = {
    '10A7': [{'line_item_id': '837234000000089050',
       'item_id': '837234000000076055',
       'name': 'Potato',
       'quantity': 10.0}],
    '20A7': [{'line_item_id': '837234000000089027',
       'item_id': '837234000000076076',
       'name': 'Apple',
       'quantity': 10.0}, 
       {'line_item_id': '837234000000095018',
       'item_id': '837234000000076055',
       'name': 'Potato',
       'quantity': 10.0}]
}

# 提取账单列,保留原字典的键顺序
bill_columns = list(f.keys())
# 初始化统计矩阵
item_stats = defaultdict(lambda: defaultdict(float))
# 逐明细累加统计
for bill_id, line_items in f.items():
    for item in line_items:
        item_name = item['name']
        item_stats[item_name][bill_id] += item['quantity']

# 写入CSV文件
with open('bill_summary.csv', 'w', newline='', encoding='utf-8') as csvfile:
    header = ['Item'] + bill_columns + ['Total']
    writer = csv.writer(csvfile)
    writer.writerow(header)
    
    for item_name, bill_counts in item_stats.items():
        # 取对应账单的累计值,无匹配则记0
        bill_values = [bill_counts.get(bill, 0.0) for bill in bill_columns]
        total_value = sum(bill_values)
        # 格式转换为整数,匹配示例输出
        row = [item_name] + [int(val) for val in bill_values] + [int(total_value)]
        writer.writerow(row)

实现效果

运行代码生成的CSV内容和预期结构完全一致:

Item,10A7,20A7,Total
Potato,10,10,20
Apple,0,10,10

实现特性

  • 支持同一账单下同一商品拆分为多条明细的场景,会自动完成数量累加,不需要预先合并同商品行
  • 如果需要避免同名不同ID的商品被错误合并,只需将统计关联维度从name调整为item_id,写入时通过映射关系取对应商品名称即可
  • 全程使用Python标准库,无额外依赖

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.17 01:54:05