使用dict键作为列名写入CSV文件

时间:2013-02-20 00:25:31

标签: python file csv

我的数据格式为dicts,如下所示:

{Color: Red, Age: 29, Date: October 2nd, Time: 4pm}

我想以这样一种方式将这些dicts写入csv,即“颜色,年龄,日期,时间”是列标题,并且字段作为行归档。这样,当我再次读取csv文件时,我得到的数据格式与上面提到的相同。

解决这个问题的正确方法是什么?

4 个答案:

答案 0 :(得分:3)

使用Pandas很容易做到这一点:

import pandas as pd

data = [
    {"A":1.0, "B":2.0, "C":"foo"},
    {"A":100, "B":20, "C":"bar"},
    {"A":0.1, "B":0.2, "C":"xyz"},
]

df = pd.DataFrame(data)

from StringIO import StringIO
buf = StringIO()
df.to_csv(buf, index=False) # convert DataFrame to csv
print buf.getvalue()

输出结果为:

A,B,C
1.0,2.0,foo
100.0,20.0,bar
0.1,0.2,xyz

加载csv:

buf.pos = 0
print pd.read_csv(buf) 

输出是:

      A     B    C
0    1.0   2.0  foo
1  100.0  20.0  bar
2    0.1   0.2  xyz

答案 1 :(得分:2)

如果您想使用标准库,可以这样做:

>>> import csv
>>> dicts = [{'Color': 'Red', 'Age': '29', 'Date': 'October 2nd', 'Time': '4pm'}, {'Color': 'Yellow', 'Age': '30', 'Date': 'September 3rd', 'Time': '5pm'}]
>>> with open('test.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile, delimiter=',',
                     quotechar='|', quoting=csv.QUOTE_MINIMAL)
    for d in dicts:
        writer.writerow([d['Color'], d['Age'], d['Date'], d['Time']])

您将在两个不同的行::

上的csv文件中获得以下输出
Red,29,October 2nd,4pm
Yellow,30,September 3rd,5pm

答案 2 :(得分:2)

使用标准csv module,您可以使用DictWriterDictReader课程来实现您的目标。

写作:

import csv

dics = [{'Color':'Red', 'Age':29, 'Date':'October 2nd', 'Time':'4pm'},
        {'Color':'Blue', 'Age':32, 'Date':'December 5th', 'Time':'6pm'},
        {'Color':'Green', 'Age':12, 'Date':'January 10th', 'Time':'2pm'}]

with open("file.csv",'wb') as f:
   # Using dictionary keys as fieldnames for the CSV file header
   writer = csv.DictWriter(f, dics[0].keys())
   writer.writeheader()
   for d in dics:
      writer.writerow(d)

阅读:

import csv

with open("file.csv", 'rb') as f:
   reader = csv.DictReader(f)
   dics = [ d for d in reader ]

>>> dics
[{'Color': 'Red', 'Date': 'October 2nd', 'Age': '29', 'Time': '4pm'},
 {'Color': 'Blue', 'Date': 'December 5th', 'Age': '32', 'Time': '6pm'},
 {'Color': 'Green', 'Date': 'January 10th', 'Age': '12', 'Time': '2pm'}]

答案 3 :(得分:1)

您可以使用csv库并从任意数据行中提取密钥名称。

import csv

file = open('filename', 'w')
writer = csv.writer(file)

writer.write(rows[0].keys())
for row in rows:
    writer.write(row)