I\'m trying to write a nested dictionary to a .csv file. Here is is a simple example:
import csv
import itertools
fields = [ \'org\', \'2015\', \'2014\', \'
Using DictWriter there is no need in sorting the fields in advance, since w.writerow() will assure the correct order. But it does make sense to sort the items themselves.
So putting together all the above suggestions and picking the best of each, i would come up with following code:
import csv
import itertools
def mergedict(a,b):
a.update(b)
return a
fields = [ 'org', '2015', '2014', '2013' ]
dw = { 'orgname1': { '2015' : 2, '2014' : 1, '2013' : 1 },
'orgname2': { '2015' : 1, '2014' : 2, '2013' : 3 },
'orgname3': { '2015' : 1, '2014' : 3, '2013' : 1 }
}
with open("test_output.csv", "wb") as f:
w = csv.DictWriter( f, fields )
w.writeheader()
for k,d in sorted(dw.items()):
w.writerow(mergedict({'org': k},d))
i added a tiny mergedict() function that makes it a one liner further down.