英文:
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文件,它应该看起来像这样:
英文:
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:
答案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 |
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论