将“词典列表”中的唯一键写入csv作为标题&还使用Python在每个标题下编写相关值

时间:2013-04-09 15:43:30

标签: python

我有一个词典列表;

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。

enter image description here

到目前为止,我已经能够像这样将独特的标题写入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的记录?

1 个答案:

答案 0 :(得分:2)

你快到了:

...
dw.writeheader()
dw.writerows(information)