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

Python如何将嵌套字典指定层级键值对应列头写入CSV文件

问题原因
  • 字段名不完整:现有代码仅将thread层级的键设置为CSV列名,未包含post首层键和social子层级的键,无法写入对应层级的内容。同时注意post首层、thread层级存在重名键(如uuid、url等),直接合并会出现值覆盖的问题,建议加前缀区分。
  • 重复写入行数异常:代码中遍历单条post时,额外嵌套了一层遍历thread键的循环,每遍历一个键就执行一次写行操作,导致单条post被重复写入多次,实际行数远大于真实数据量。
修正代码
import csv

# 拆分各层级键,重命名避免重名冲突
post_base_keys = [k for k in output['posts'][0].keys() if k != 'thread']
thread_keys = [f"thread_{k}" for k in output['posts'][0]['thread'].keys() if k != 'social']
social_keys = [f"social_{k}" for k in output['posts'][0]['thread']['social'].keys()]
# 合并所有列名
all_fieldnames = post_base_keys + thread_keys + social_keys

with open('file.csv', 'w', encoding='utf-8', newline='') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=all_fieldnames)
    writer.writeheader()
    # 直接遍历所有post,不需要额外嵌套循环
    for post in output['posts']:
        row_dict = {}
        # 写入post首层内容
        for k in post_base_keys:
            row_dict[k] = post[k]
        # 写入thread层级内容
        thread_data = post['thread']
        for k in thread_data.keys():
            if k != 'social':
                row_dict[f"thread_{k}"] = thread_data[k]
        # 写入social层级内容
        social_data = thread_data['social']
        for k in social_data.keys():
            row_dict[f"social_{k}"] = social_data[k]
        # 单条post仅写入一次
        writer.writerow(row_dict)

如果不需要给重名键加前缀,仅调整键的命名逻辑即可,核心逻辑是移除嵌套的写行循环、将三个层级的内容合并到同一行字典中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 03:54:01