如何将此字典列表转换为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
toCSV = [{'name':'bob','age':25,'weight':200},
{'name':'jim','age':31,'weight':180}]
keys = toCSV[0].keys()
with open('people.csv', 'wb') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(toCSV)
我先前的解决方案不处理订单.正如Wilduck所指出的,此处DictWriter更合适.
My prior solution doesn't handle the order. As noted by Wilduck, DictWriter is more appropriate here.
这篇关于如何将此字典列表转换为csv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文