Python 使用字典列表写入.csv文件
我有以下词典列表:Python 使用字典列表写入.csv文件,python,list,python-2.7,csv,dictionary,Python,List,Python 2.7,Csv,Dictionary,我有以下词典列表: [{'Eva': 5}, {'Ana': 53}, {'Ada': 12}] 我需要获取此列表并制作一个.csv文件,因此输出需要如下所示: 我有这段代码,但它给了我错误,所以我真的不知道在这一点上该怎么做 import csv file = [{'Eva': 5}, {'Ana': 53}, {'Ada': 12}] keys = file[0].keys() with open('output.csv','wb') as output_file: dict_
[{'Eva': 5}, {'Ana': 53}, {'Ada': 12}]
我需要获取此列表并制作一个.csv文件,因此输出需要如下所示:
我有这段代码,但它给了我错误,所以我真的不知道在这一点上该怎么做
import csv
file = [{'Eva': 5}, {'Ana': 53}, {'Ada': 12}]
keys = file[0].keys()
with open('output.csv','wb') as output_file:
dict_writer = csv.DictWriter(output_file,keys)
dict_writer.writeheader()
dict_writer.writerows(file)
代码可以是这样的
import csv
fieldnames = ["Owner's Names", "Average Age"]
file = [{'Eva': 5}, {'Ana': 53}, {'Ada': 12}]
with open('output.csv', 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for f in file:
writer.writerow({fieldnames[0]: f.keys()[0], fieldnames[1]: f.values()[0]})
我希望它能有所帮助 比“错误”更具体,给出一个。它给了我一个值错误:dict包含字段名中没有的字段:“Ana”错误在
dict\u writer=csv行中。DictWriter(输出文件,键)
。变量keys
为false。最好使用[('Eva',5),('Ana',53),('Ada',12)]
而不是[{'Eva':5},{'Ana':53},{'Ada':12}]
。我需要它与字典列表一起使用,这样我就不能使用[('Eva',5..)等)这非常有用,现在该函数正在正常工作。谢谢:)