如何在Python中将嵌套字典放入CSV中

huangapple go评论70阅读模式
英文:

How to put nested dictionary in csv in python

问题

以下是一个嵌套字典:

nested_dict = {
    '水果': {
        'A': [1, 2, 3, 4, 5],
        'B': [5, 4, 3, 2, 1],
        'C': [11, 12, 13, 14, 15]
    },
    '蔬菜': {
        'A': [11, 12, 13, 14, 15],
        'B': [15, 14, 13, 12, 11],
        'C': [25, 24, 23, 22, 21]
    }
}

我想将这个嵌套字典导出为CSV文件,它应该看起来像这样:

如何在Python中将嵌套字典放入CSV中

英文:

Following is a nested dictionary:

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]
    }
}

I want this nested dictionary to be exported in csv and it should look something like this:

如何在Python中将嵌套字典放入CSV中

答案1

得分: 1

考虑使用 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]
    }
}

with open('output.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['', 'A', 'B', 'C'])
    for category, values in nested_dict.items():
        for i in range(len(values['A'])):
            row = [category] + [values[key][i] for key in ['A', 'B', 'C']]
            writer.writerow(row)

output.csv

A B C
Fruit 1 5 11
Fruit 2 4 12
Fruit 3 3 13
Fruit 4 2 14
Fruit 5 1 15
Vegetable 11 15 25
Vegetable 12 14 24
Vegetable 13 13 23
Vegetable 14 12 22
Vegetable 15 11 21
英文:

Consider utilizing the csv module:

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]
    }
}

with open('output.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['', 'A', 'B', 'C'])
    for category, values in nested_dict.items():
        for i in range(len(values['A'])):
            row = [category] + [values[key][i] for key in ['A', 'B', 'C']]
            writer.writerow(row)

output.csv:

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

huangapple
  • 本文由 发表于 2023年7月14日 07:43:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76683885.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定