我有一个字典列表,看起来像这样:
toCSV = [{'name':'bob','age':25,'weight':200},{'name':'jim','age':31,'weight':180}]
我应该做什么来将它转换成一个csv文件,看起来像这样:
name,age,weight
bob,25,200
jim,31,180
我有一个字典列表,看起来像这样:
toCSV = [{'name':'bob','age':25,'weight':200},{'name':'jim','age':31,'weight':180}]
我应该做什么来将它转换成一个csv文件,看起来像这样:
name,age,weight
bob,25,200
jim,31,180
当前回答
熊猫的短期解决方案
import pandas as pd
list_of_dicts = [
{'name': 'bob', 'age': 25, 'weight': 200},
{'name': 'jim', 'age': 31, 'weight': 180},
]
df = pd.DataFrame(list_of_dicts)
df.to_csv("names.csv", index=False)
其他回答
熊猫的短期解决方案
import pandas as pd
list_of_dicts = [
{'name': 'bob', 'age': 25, 'weight': 200},
{'name': 'jim', 'age': 31, 'weight': 180},
]
df = pd.DataFrame(list_of_dicts)
df.to_csv("names.csv", index=False)
这是当你有一个字典列表时:
import csv
with open('names.csv', 'w') as csvfile:
fieldnames = ['first_name', 'last_name']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
下面是另一个更通用的解决方案,假设你没有行列表(可能它们不适合内存)或头文件的副本(可能write_csv函数是通用的):
def gen_rows():
yield OrderedDict(name='bob', age=25, weight=200)
yield OrderedDict(name='jim', age=31, weight=180)
def write_csv():
it = genrows()
first_row = it.next() # __next__ in py3
with open("people.csv", "w") as outfile:
wr = csv.DictWriter(outfile, fieldnames=list(first_row))
wr.writeheader()
wr.writerow(first_row)
wr.writerows(it)
注意:此处使用的OrderedDict构造函数仅在python >3.4中保留顺序。如果顺序很重要,请使用OrderedDict([('name', 'bob'),('age',25)])形式。
import csv
toCSV = [{'name':'bob','age':25,'weight':200},
{'name':'jim','age':31,'weight':180}]
header=['name','age','weight']
try:
with open('output'+str(date.today())+'.csv',mode='w',encoding='utf8',newline='') as output_to_csv:
dict_csv_writer = csv.DictWriter(output_to_csv, fieldnames=header,dialect='excel')
dict_csv_writer.writeheader()
dict_csv_writer.writerows(toCSV)
print('\nData exported to csv succesfully and sample data')
except IOError as io:
print('\n',io)
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)