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

如何将数据库返回的字典列表值匹配CSV指定表头写入文件?

解决CSV文件表头与字典键映射写入问题

原代码存在的问题

  • 硬编码取值时,字典中不存在account_id键,会触发KeyError
  • 将所有数据追加到同一个values列表,最终只会写入一行数据,而非每条字典对应一行
  • 未处理表头与字典键的映射关系(如salesorder_id对应salesorder id、invoicedate对应invoice date)

解决方案

使用csv.DictWriter可以便捷处理表头与字典键的映射,同时自动处理缺失字段的默认值,具体实现如下:

import csv

# 固定CSV表头
header = ['subject', 'salesorder id', 'invoice date', 'account id']
# 定义表头到字典键的映射规则
header_key_map = {
    'subject': 'subject',
    'salesorder id': 'salesorder_id',
    'invoice date': 'invoicedate',
    'account id': 'account_id'
}
# 数据库查询返回的字典列表
result = [
    {'subject': 'SR Release 2 Intranet', 'salesorder_id': '', 'customerno': '', 'contact_id': '4x4395', 'invoicedate': '2009-04-27', 'duedate': '2009-05-15'},
    {'subject': 'Rechnung::ZChL::TP01::Relaunch::1.Rate', 'salesorder_id': '', 'customerno': '', 'contact_id': '4x8151', 'invoicedate': '2009-07-09', 'duedate': '2009-07-09'}
]

# 转换数据格式,匹配表头要求
formatted_data = []
for item in result:
    row = {}
    for col in header:
        # 安全获取对应值,键不存在时返回空字符串
        row[col] = item.get(header_key_map[col], '')
    formatted_data.append(row)

# 写入CSV文件
with open('myFile.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.DictWriter(f, fieldnames=header)
    writer.writeheader()  # 写入表头
    writer.writerows(formatted_data)  # 批量写入数据行

代码说明

  • header_key_map:明确表头与字典键的对应关系,解决命名不一致的问题
  • item.get(header_key_map[col], ''):避免因字典缺失键导致的报错,缺失时自动填充空值
  • csv.DictWriter:专为字典数据写入CSV设计,writerows可一次性写入所有数据行
  • newline='':解决Windows系统下CSV文件出现空行的问题
  • encoding='utf-8':保证特殊字符正常存储

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 17:17:02