如何将这个词典列表转换为csv文件? [蟒蛇] [英] How do I convert this list of dictionaries to a csv file? [Python]
本文介绍了如何将这个词典列表转换为csv文件? [蟒蛇]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似这样的字典列表:
toCSV = [{'name':'bob' ,'age':25,'weight':200},{'name':'jim','age':31,'weight':180}]
我应该怎么做将其转换为类似这样的csv文件:
姓名,年龄,体重
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。编辑:我的以前的解决方案不处理订单。。。。。。。。。。。正如Wilduck所指出的,DictWriter在这里更合适。
I have a list of dictionaries that looks something like this:
toCSV = [{'name':'bob','age':25,'weight':200},{'name':'jim','age':31,'weight':180}]
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)
EDIT: My prior solution doesn't handle the order. As noted by Wilduck, DictWriter is more appropriate here.
这篇关于如何将这个词典列表转换为csv文件? [蟒蛇]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文