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

Python如何更简洁地合并两个字典列表的指定字段并写入CSV

实现方案

你可以先把两个数据集的已知键按CSV输出的预期顺序提前定义为常量列表,之后批量调用get方法取值即可,无需手动输入44次键名:

第一步:定义键顺序列表

# 订阅数据集键列表,顺序和CSV要输出的订阅字段顺序一致
SUB_KEYS = [
    'name', 'trial', 'status', 'startDate', 'serviceGate', 'lastBillDate', 
    'nextBillDate', 'autoRenewDate', 'serviceStatus', 'expirationDate', 
    'subscriptionId', 'autoRenewEnabled', 'billingTerms.autoRenewal.days', 
    'billingTerms.autoRenewal.type', 'billingTerms.billingModel', 
    'billingTerms.freezePrices', 'billingTerms.billingPeriod.unit', 
    'billingTerms.billingPeriod.duration', 'subscriptionPeriod.unit', 
    'subscriptionPeriod.duration', 'account.id'
]

# 资源数据集键列表,顺序和CSV要输出的资源字段顺序一致
RES_KEYS = [
    'resource.resourceId', 'resource.MPNumber', 'resource.internalResourceId', 
    'resource.status', 'resource.unitOfMeasureId', 'resource.measurable', 
    'resource.showInCustomerPanel', 'resource.allowToModifyInTrial', 
    'resource.included', 'resource.additional', 'resource.ordered', 'resource.min', 
    'resource.max', 'resource.vendorSubscriptionId', 'resource.usage', 
    'resource.consumptionType', 'resource.name.en_US', 'resource.name.fr_FR', 
    'resource.name.nl_NL', 'resource.unitOfMeasure.en_US', 'resource.unitOfMeasure.fr_FR', 
    'resource.unitOfMeasure.nl_NL'
]

第二步:批量生成行数据并写入CSV

import csv

master_data = []
# 可选:添加表头行,方便后续读取CSV时识别字段
master_data.append(SUB_KEYS + RES_KEYS)

# 原逻辑为订阅和资源做笛卡尔积,每个订阅匹配所有资源生成一行
for sub in subscriptions:
    for res in resources:
        # 批量按顺序取订阅字段值,键不存在默认返回空字符串,可按需修改默认值
        sub_row = [sub.get(k, "") for k in SUB_KEYS]
        # 批量按顺序取资源字段值
        res_row = [res.get(k, "") for k in RES_KEYS]
        master_data.append(sub_row + res_row)

# 写入CSV,新增newline参数避免Windows下生成多余空行,utf-8-sig编码兼容Excel打开不乱码
with open("out.csv", "w", newline="", encoding="utf-8-sig") as out_file:
    writer = csv.writer(out_file, delimiter=",")
    writer.writerows(master_data)

补充说明

如果你的业务逻辑中订阅和资源是一一对应关系(即下标相同的订阅和资源为一组),可以将嵌套循环替换为zip遍历,效率更高:

for sub, res in zip(subscriptions, resources):
    sub_row = [sub.get(k, "") for k in SUB_KEYS]
    res_row = [res.get(k, "") for k in RES_KEYS]
    master_data.append(sub_row + res_row)

后续如果需要调整字段顺序、增删字段,只需修改SUB_KEYS和RES_KEYS两个列表即可,无需修改取值逻辑,维护成本更低。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:45:02