我有一个如下所示的数据结构:
data =[
{'key_1': { 'calc1': 42, 'calc2': 3.142 } },
{'key_2': { 'calc1': 123.4, 'calc2': 1.414 } },
{'key_3': { 'calc1': 2.718, 'calc2': 0.577 } }
]
Run Code Online (Sandbox Code Playgroud)
我希望能够使用以下格式将数据保存/加载到CSV文件中
key, calc1, calc2 <- header
key_1, 42, 3.142 <- data rows
key_2, 123.4, 1.414
key_3, 2.718, 0.577
Run Code Online (Sandbox Code Playgroud)
什么是从这样的CSV文件中读取/保存此数据结构的"Pythonic"方法?
只是为了显示一个使用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
Run Code Online (Sandbox Code Playgroud)
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())
Run Code Online (Sandbox Code Playgroud)