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

Python中如何将嵌套字典导出为CSV文件

将嵌套字典导出为指定格式CSV

可以用Python内置的csv模块实现需求,以下是具体代码和说明:

实现代码

import csv

nested_dict = {
    'Fruit': {
        'A': [1, 2, 3, 4, 5],
        'B': [5, 4, 3, 2, 1],
        'C': [11, 12, 13, 14, 15]

    },
    'Vegetable': {
        'A': [11, 12, 13, 14, 15],
        'B': [15, 14, 13, 12, 11],
        'C': [25, 24, 23, 22, 21]
    }
}

# 定义CSV表头:类别、子类别、列1到列5
header = ['类别', '子类别', '列1', '列2', '列3', '列4', '列5']

# 打开CSV文件并写入内容
with open('output.csv', 'w', newline='', encoding='utf-8') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(header)
    
    # 遍历外层字典(类别)
    for category, sub_categories in nested_dict.items():
        # 遍历内层字典(子类别)
        for sub_cat, values in sub_categories.items():
            # 拼接一行数据:类别 + 子类别 + 列表元素
            row = [category, sub_cat] + values
            writer.writerow(row)

输出的CSV内容

运行代码后生成的output.csv内容如下:

类别,子类别,列1,列2,列3,列4,列5
Fruit,A,1,2,3,4,5
Fruit,B,5,4,3,2,1
Fruit,C,11,12,13,14,15
Vegetable,A,11,12,13,14,15
Vegetable,B,15,14,13,12,11
Vegetable,C,25,24,23,22,21

代码逻辑说明

  • 先定义符合需求的表头,明确每一列的含义
  • 逐层遍历嵌套字典的层级:先遍历外层的类别(Fruit/Vegetable),再遍历每个类别下的子类别(A/B/C)
  • 将每个子类别对应的列表数据展开为CSV的列,拼接成完整行后写入文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 14:17:04