I have a list of dictionaries like that :
[
{'item1':'bla', 'item2':'bli', 'item3':'blu'},
{'item1'开发者_开发技巧:'love', 'item3':'python'}
]
Notice that dict 2 doesn't have key 'item2'. I want to produce a csv output as such, so I can insert everything into a SQL table:
item1,item2,item3
bla,bli,blu
love,,python
I found an easy way to do that if all dictionaries share the same keys, but I don't see how to do that elegantly if that is not the case.
Use csv.DictWriter
with the fieldnames
and restval
arguments.
Something like
#Create a master list of keys
allKeys = ()
for row in YourListHere:
allKeys.union(row.keys())
#Sort the keys
allKeys = list(allKeys).sorted()
#Go through printing the rows
for row in YourListHere:
values = []
for key in allKeys:
#Add the values if it exists, if no key in this row add a blank
if key in row:
values.append(row[key])
else:
values.append('')
print ','.join(values)
精彩评论