简体   繁体   English

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

[英]Writing to a CSV file with dict keys as column names

I have data in the format of dicts as follows: 我有dicts格式的数据如下:

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

And I want to write these dicts to a csv in such a way that the "Color, age, date, time" are the column titles, and the fields get filed in as the rows. 我想以这样的方式将这些dicts写入csv,即“颜色,年龄,日期,时间”是列标题,并且字段作为行归档。 That way, when I read the csv file again, I get the data formatted in the same way mentioned above. 这样,当我再次读取csv文件时,我得到的数据格式与上面提到的方式相同。

What is the proper way to go about this? 什么是正确的方法来解决这个问题?

It's very easy to do this with Pandas: 使用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()

The output is: 输出是:

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

To load csv: 要加载csv:

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

the output is: 输出是:

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

Using the standard csv module you can use DictWriter and DictReader classes for achieving what you want. 使用标准csv模块,您可以使用DictWriterDictReader类来实现您想要的功能。

for writing: 写作:

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)

for reading: 阅读:

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

If you want to use a standard library, you could do this: 如果要使用标准库,可以执行以下操作:

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

You will get the following output in a csv file on two different lines:: 您将在两个不同的行上的csv文件中获得以下输出::

Red,29,October 2nd,4pm
Yellow,30,September 3rd,5pm

You can use the csv library and extract the key names from an arbitrary data row. 您可以使用csv库并从任意数据行中提取键名。

import csv

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM