我有一个字典列表,看起来像这样:

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 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)

这是当你有一个字典列表时:

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'})

在python 3中,事情有点不同,但更简单,更不容易出错。告诉CSV你的文件应该使用utf8编码打开,这是一个好主意,因为它使数据更容易移植到其他人(假设你没有使用更严格的编码,如latin1)

import csv
toCSV = [{'name':'bob','age':25,'weight':200},
         {'name':'jim','age':31,'weight':180}]
with open('people.csv', 'w', encoding='utf8', newline='') as output_file:
    fc = csv.DictWriter(output_file, 
                        fieldnames=toCSV[0].keys(),

                       )
    fc.writeheader()
    fc.writerows(toCSV)

注意,python 3中的csv需要newline= "参数,否则在excel/opencalc中打开csv时会得到空行。

或者:我更喜欢使用pandas模块中的csv处理程序。我发现它对编码问题更宽容,并且pandas在加载文件时会自动将csv中的字符串数字转换为正确的类型(int,float等)。

import pandas
dataframe = pandas.read_csv(filepath)
list_of_dictionaries = dataframe.to_dict('records')
dataframe.to_csv(filepath)

注意:

pandas will take care of opening the file for you if you give it a path, and will default to utf8 in python3, and figure out headers too. a dataframe is not the same structure as what CSV gives you, so you add one line upon loading to get the same thing: dataframe.to_dict('records') pandas also makes it much easier to control the order of columns in your csv file. By default, they're alphabetical, but you can specify the column order. With vanilla csv module, you need to feed it an OrderedDict or they'll appear in a random order (if working in python < 3.5). See: Preserving column order in Python Pandas DataFrame for more.

熊猫的短期解决方案

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
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)