2

我有一个字典列表;

information = [{'Edu':'School','Age':'40','Height':'5.11','DOB':'08091972','Name':'Jack'},
 {'Edu':'College','Age':'30','Height':'4.11','DOB':'05041982','Name':'Alex','Pro':'Teacher'},
 {'Name':'Elizabeth','Nickname':'Lizzy','DOB':'01012005'}]

我想把它写到一个csv中。

在此处输入图像描述

到目前为止,我已经能够像这样将唯一的标头写入 csv...

unique_headers = []

for info in information:
    unique_headers.append(s.keys()) # append keys to a list - but this would take ages right? certainly not pythonic


ordered_fieldnames = set(flatten(unique_headers))

with open('profile.csv','wb') as fou:
    dw = csv.DictWriter(fou, delimiter=',', fieldnames=ordered_fieldnames)
    dw.writeheader() # unique headers are written

现在,如何将记录写入相关标题下的 csv 中?

4

1 回答 1

2

你快到了:

...
dw.writeheader()
dw.writerows(information)
于 2013-04-09T16:02:41.417 回答