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

Python 3.9中含发票字段的字典列表去重转指定JSON格式

处理含重复字段的字典列表并生成指定JSON格式

需求说明

读取得到的文件数据是包含5列的字典列表,因INVOICE字段存在,导致前4列(ID、ID_A、ID_B、ID_C)数据重复。需在Python 3.9环境下将其转换为无重复的指定JSON格式,在原有无重复场景的转换代码基础上,添加INVOICE字段且不产生重复行。

示例输入

test_dict = [
    {'ID':"A", 'ID_A':"A1",'ID_B':"A2",'ID_C':"A3",'INVOICE':"123"},
    {'ID':"A", 'ID_A':"A1",'ID_B':"A2",'ID_C':"A3",'INVOICE':"345"}
]

原无重复场景转换代码

from collections import defaultdict

result = defaultdict(set)
for i in test_dict:
    id = i.get('ID')
    if id:
        result[id].add(i.get('ID_A'))
        result[id].add(i.get('ID_B'))
        result[id].add(i.get('ID_C'))

output = []
for id, details in result.items():
    output.append(
        {
            "ID": id,
            "otherDetails": {
                "IDs": [
                    {"id": ref} for ref in details
                ]
            },
        }
    )

期望输出

[
    {
        'ID': 'A',
        'OtherDetails': {
            'IDs': [{'id': 'A1'}, {'id': 'A2'}, {'id': 'A3'}],
            'INVOICE': [{'id':'123'}, {'id':'345'}]
        }
    }
]

修改后的实现代码

from collections import defaultdict

# 调整result结构,存储每个ID对应的ID集合和INVOICE集合
result = defaultdict(lambda: {'ids': set(), 'invoices': set()})

for item in test_dict:
    current_id = item.get('ID')
    if current_id:
        # 收集ID_A、ID_B、ID_C
        result[current_id]['ids'].add(item.get('ID_A'))
        result[current_id]['ids'].add(item.get('ID_B'))
        result[current_id]['ids'].add(item.get('ID_C'))
        # 收集INVOICE字段
        invoice_num = item.get('INVOICE')
        if invoice_num:
            result[current_id]['invoices'].add(invoice_num)

output = []
for id_val, details in result.items():
    output.append(
        {
            "ID": id_val,
            "OtherDetails": {
                "IDs": [{"id": ref} for ref in details['ids']],
                "INVOICE": [{"id": inv} for inv in details['invoices']]
            },
        }
    )

print(output)

代码说明

  1. 调整result的结构,使用defaultdict生成包含ids和invoices两个集合的字典,分别存储去重后的关联ID和发票号。
  2. 遍历原字典列表时,同时收集ID_A/B/C和INVOICE字段,利用集合自动去重的特性避免重复值。
  3. 构造输出时,将两个集合分别转换为指定的字典列表格式,确保最终输出符合要求且无重复行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 02:25:16