将 Python 字典转换为 .csv 文件

时间:2020-12-23 07:47:51

标签: python

我想将我的 python 字典转换为 .csv 文件,其中字典由“关键字值”:[listofdata] 表示我希望我的 csv 文件以这样的方式查看关键字值是 csv 文件中的列和列表中的数据将留在与键对应的列中。 示例 -->

my_dict={"date":['11/2/19','3/11/20'],"name":['dexter','morgan']

CSV_file 输出 -->

date,name
'11/2/19','dexter'
'3/11/20','morgan'

2 个答案:

答案 0 :(得分:2)

使用 csv 模块:

import csv

field_names = ['Date', 'Name']

my_dict=[{"date":'11/2/19',"name":'dexter'}, {"date":'3/11/20',"name":'morgan'}]

with open('file.csv', 'w') as csvfile: 
    writer = csv.DictWriter(csvfile, fieldnames = field_names) 
    writer.writeheader() 
    writer.writerows(my_dict)

欲了解更多信息,请检查: https://www.geeksforgeeks.org/how-to-save-a-python-dictionary-to-a-csv-file/

答案 1 :(得分:0)

你将不得不稍微修改一下你的字典,但这样的事情会起作用:

import csv

field_names = ['date', 'name']

my_dict={"date":['11/2/19','3/11/20'],"name":['dexter','morgan']}

with open('file.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(field_names)
    rows = zip(*[my_dict[name] for name in field_names])
    writer.writerows(rows)

zip 的这种用法是“转置”的常用习语,因此:

zip(*[my_dict[name] for name in field_names])

例如:

In [2]: my_dict={"date":['11/2/19','3/11/20'],"name":['dexter','morgan']}

In [2]: field_names = ['date', 'name']

In [3]: list(zip(*[my_dict[name] for name in field_names]))
Out[3]: [('11/2/19', 'dexter'), ('3/11/20', 'morgan')]