223

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

toCSV = [{'name':'bob','age':25,'weight':200},{'name':'jim','age':31,'weight':180}]

我应该怎么做才能将其转换为如下所示的 csv 文件:

name,age,weight
bob,25,200
jim,31,180
4

7 回答 7

402
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)
于 2010-06-21T17:41:08.137 回答
31

在 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)
  • 请注意,csv在 python 3 中需要该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 会帮你打开文件,并且默认utf8在 python3 中,并找出标题。
  • 数据框与 CSV 提供的结构不同,因此您在加载时添加一行以获得相同的内容:dataframe.to_dict('records')
  • pandas 还可以更轻松地控制 csv 文件中的列顺序。默认情况下,它们是按字母顺序排列的,但您可以指定列顺序。使用 vanillacsv模块,您需要为其提供一个OrderedDict或它们将以随机顺序出现(如果在 python < 3.5 中工作)。有关更多信息,请参阅:在 Python Pandas DataFrame中保留列顺序。
于 2019-02-12T17:21:51.177 回答
17

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

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'})
于 2015-02-13T23:03:37.837 回答
8

因为@User 和@BiXiC 在这里寻求有关 UTF-8 的帮助,这是@Matthew 解决方案的变体。(我不允许评论,所以我正在回答。)

import unicodecsv as 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)
于 2017-02-26T16:45:34.247 回答
2
import csv

with open('file_name.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(('colum1', 'colum2', 'colum3'))
    for key, value in dictionary.items():
        writer.writerow([key, value[0], value[1]])

这是将数据写入.csv文件的最简单方法

于 2018-04-19T03:35:51.673 回答
2

这是另一个更通用的解决方案,假设您没有行列表(可能它们不适合内存)或标题副本(可能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)])表格。

于 2018-03-22T16:25:32.087 回答
1
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)
于 2020-01-13T08:30:21.547 回答