Python: Writing Nested Dictionary to CSV

前端 未结 5 589
庸人自扰
庸人自扰 2020-12-08 16:38

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\', \'         


        
5条回答
  •  一整个雨季
    2020-12-08 17:08

    Alternative implementation using DictWriter and with headers

    import csv
    import itertools
    
    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 in dw:
            w.writerow({field: dw[k].get(field) or k for field in fields})
    

    Output:

    org,2015,2014,2013
    orgname1,2,1,1
    orgname3,1,3,1
    orgname2,1,2,3
    

提交回复
热议问题