Using DictWriter, there is no need to sort the fields in advance, since w.writerow() will provide the correct order. But it makes sense to sort the elements yourself.
Thus, having collected all the above suggestions and choosing the best of them, I came up with the 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 function mergedict() , which makes it another liner.
source share