2010-07-07 63 views
2

我有一个数据结构,看起来像这样:读/从一个CSV文件中写入的嵌套字典到/清单(Python)的

data =[ 
{'key_1': { 'calc1': 42, 'calc2': 3.142 } }, 
{'key_2': { 'calc1': 123.4, 'calc2': 1.414 } }, 
{'key_3': { 'calc1': 2.718, 'calc2': 0.577 } } 
] 

我希望能够保存/和数据加载到以CSV格式如下

key, calc1, calc2 <- header 
key_1, 42,  3.142 <- data rows 
key_2, 123.4, 1.414 
key_3, 2.718, 0.577 

什么是“Python化”的方式来读/这个数据结构从CSV保存/文件像上面的文件?

+0

出于兴趣,为什么你会使用一个长度为1字节的字典列表,而不是一个长度为字典的字典? – naught101 2012-07-30 04:12:14

回答

5

我不认为这将有可能使用csv模块,由于您的要求的所有特质和结构,但你可以做到这一点很容易手动写它:

>>> with open('test.txt', 'w') as f: 
    f.write(','.join(['key', 'calc1', 'calc2']) + '\n') 
    f.writelines('{},{},{}'.format(k, *v.values()) + '\n' for l in data for k,v in l.items()) 
+0

@silentghost:对于漂亮和短的代码段为+1。我相信我会提出什么,会更加冗长。然而,随着简洁性的提高,“蜻蜓”水平就会提升。你能解释第三行 - 参数传递给writelines()吗?谢谢。 – morpheous 2010-07-07 15:16:00

+0

也许是一个说明,该格式只适用于Python版本的2.6以上 – Tshepang 2010-07-07 15:24:41

+0

它只是一个字符串的迭代器。每个格式都是一个逗号分隔的列表,由于'data'的嵌套性,我必须迭代两次。 – SilentGhost 2010-07-07 15:26:01

6

刚显示一个版本,它使用csv模块:

from csv import DictWriter 

data =[ 
{'key_1': { 'calc1': 42, 'calc2': 3.142 } }, 
{'key_2': { 'calc1': 123.4, 'calc2': 1.414 } }, 
{'key_3': { 'calc1': 2.718, 'calc2': 0.577 } } 
] 

with open('test.csv', 'wb') as f: 
    writer = DictWriter(f, ['key', 'calc1', 'calc2']) 
    writer.writerow(dict(zip(writer.fieldnames, writer.fieldnames))) # no automatic header :-(
    for i in data: 
     key, values = i.items()[0] # each dict in data contains only one entry 
     writer.writerow(dict(key=key, **values)) # first make a new dict merging the key and the values 
+0

你应该能够使用'writer.writeheader()'写出头文件。 (截至2.7):-) – 2016-09-01 23:14:23

-1

我觉得目前为止最简单的方法是把字典第一成大熊猫数据帧,并从那里很方便到CSV文件中。

import pandas as pd  
df = pd.DataFrame.from_dict(data, orient='index') # it is either ‘columns’ or ‘index’ (simple transpose) 
    df.to_csv('filepath/name.csv') 

加载文件回字典形式

df.to_csv('filepath/name.csv') 
data_dict = df.to_dict() 

对于更复杂的情况下,看看到大熊猫文档 http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_dict.htmlhttp://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_dict.html