我有一本字典,但每个键都有不同数量的字典作为值。此外,嵌套字典的键可以采用三种不同的形式。
myDict = {
u'A': {'1998': u'ATLANTA'},
u'B': {'1999': u'MANNHEIM'},
u'C': {'2000': u'BERLIN'},
u'D': {'1998': u'CHICAGO', '1999': u'PRINCETON'},
u'E': {'2000': u'LOUISIANA'},
u'F': {'1998': u'NEW YORK', '1999': u'NEW YORK'}
}
我想写成myDict
一个看起来像的表格
| 1998 | 1999 | 2000
A | ATLANTA | |
B | | MANNHEIM |
C | | | BERLIN
D | | CHICAGO | PRINCETON
E | | | LOUISANA
F | NEW YORK | NEW YORK |
我该怎么做?我尝试使用 aDictWriter
和 a Writer
from csv
,但两者都不起作用:
DictWriter
:
import csv
with open("outfilename.csv", 'w') as f:
fieldnames = ['author', '1998', '1999', '2000']
csvWriter = csv.DictWriter(f, fieldnames)
csvWriter.writerows(myDict)
结果是:
File "./011_create_node_lists.py", line 122, in <module>
csvWriter.writerows(myDict)
File "/usr/lib/python2.7/csv.py", line 157, in writerows
rows.append(self._dict_to_list(rowdict))
File "/usr/lib/python2.7/csv.py", line 149, in _dict_to_list
return [rowdict.get(key, self.restval) for key in self.fieldnames]
AttributeError: 'unicode' object has no attribute 'get'
writer
:
import csv
with open("outfilename.csv", 'w') as f:
csvWriter = csv.writer(f)
for key, value in myDict.items():
csvWriter.writerow([key, value])
结果是:
A | {'1998': u'ATLANTA'}
B | {'1999': u'MANNHEIM'}
C | {'2000': u'BERLIN'}
D | {'1998': u'CHICAGO' | '1999': u'PRINCETON'}
E | {'2000': u'LOUISIANA'}
F | {'1998': u'NEW YORK' | '1999': u'NEW YORK'}
此外,我什至不确定这是否是打印结构化表格的最佳方式。