我尝试用csv的公共密钥编写一些字典,但一直遇到一个关键错误:
TotalData = dict1, dict2, dict3
with open(self.pathString, 'wb') as ofile:
writer = csv.writer(ofile, quoting=csv.QUOTE_NONE, delimiter='\t')
writer.writerow(['field1', 'field2', 'field3'])
for key in sorted(ConsoSom.iterkeys(), key=lambda x: str(x)):
writer.writerow([key] + ['{0:.2f}'.format(d[key]) for d in TotalData])
我的错误给了我KeyError:u'dict3key'
更新:这是因为密钥并不总是存在。我想知道如果钥匙不存在,如何留一个空格。
我想要的结果是:
field1, field2, field3
id1, value1, second1
id2, , second2
id3, value3, second3
答案 0 :(得分:2)
使用dict.get
:
TotalData = dict1, dict2, dict3
with open(self.pathString, 'wb') as ofile:
writer = csv.writer(ofile, quoting=csv.QUOTE_NONE, delimiter='\t')
writer.writerow(['field1', 'field2', 'field3'])
for key in sorted(ConsoSom.iterkeys(), key=lambda x: str(x)):
writer.writerow([key] + ['{0:.2f}'.format(d.get(key, 0)) for d in TotalData])