gpt4 book ai didi

python - 如何将嵌套字典中的键输出到csv

转载 作者:太空宇宙 更新时间:2023-11-03 17:44:39 28 4
gpt4 key购买 nike

我正在尝试将嵌套字典写入 CSV。我已经能够成功地做到这一点,但是因为字典没有排序,所以我无法分辨哪一列是哪一列。如何将键输出为列标题,以便我可以区分哪一列?

import datetime
import csv

d = {
u'Project 1': {'Start Date': datetime.datetime(2015, 5, 6, 0, 0), 'Finish Date': datetime.datetime(2015, 12, 23, 0, 0)},
u'Project 2': {'Start Date': datetime.datetime(2015, 1, 23, 0, 0), 'Finish Date': datetime.datetime(2015, 12, 22, 0, 0)}
}

milestones = d.values()[0].keys()
for key, value in d.items():
print [key] + [d[key][date] for date in milestones]

writer = csv.writer(open('C:\\test.csv', 'wb'))
for key, value in d.items():
writer.writerow([key] + [d[key][date] for date in milestones])

最佳答案

使用csv.DictWriter (这是一个示例,请根据您的需要进行修改):

import csv

with open('test.csv', 'w') as csvfile:
# put all keys you want to write here
fieldnames = ['Project Name', 'Start Date', 'Finish Date']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()

for project_name, project_dict in d.iteritems():
# add project name
row_dict = dict(
[("Project Name", project_name)] + project_dict.items()
)
# write row
writer.writerow(row_dict)

关于python - 如何将嵌套字典中的键输出到csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29993499/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com