如何将此字典列表转换为 csv 文件? [英] How do I convert this list of dictionaries to a csv file?
本文介绍了如何将此字典列表转换为 csv 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的字典列表:
I have a list of dictionaries that looks something like this:
toCSV = [{'name':'bob','age':25,'weight':200},{'name':'jim','age':31,'weight':180}]
我应该怎么做才能将其转换为如下所示的 csv 文件:
What should I do to convert this to a csv file that looks something like this:
name,age,weight
bob,25,200
jim,31,180
推荐答案
import csv
to_csv = [
{'name': 'bob', 'age': 25, 'weight': 200},
{'name': 'jim', 'age': 31, 'weight': 180},
]
keys = to_csv[0].keys()
with open('people.csv', 'w', newline='') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(to_csv)
这篇关于如何将此字典列表转换为 csv 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文