Printing nested dicts to CSV in Python -
i parsing text files , keeping track of number of programs, software versions, , counts of versions' occurrences, in following structure:
{excel: {'1.2.1':2, '2.1.1':55, '3.4.5':12}, adobe: {'1.1.1':4, '5.4.4':12, '4'3.3':8}[...]}
etc.
how can print neatly csv output this:
program,version,count excel,1.2.1,2 excel,2.1.1,55 excel,3.4.5,12 adobe,1.1.1,4 adobe,5.4.4,12 adobe,4.3.3,8
i have done lot of searching , haven't been able find need. appreciated!
edit:
here have tried, think comes close, isn't right based on output get:
for prod,version in products.iteritems(): p in prod: v in version: outfile.write('%s,%s,%d\n' % (p,v,version[v]))
where products name of outer dict.
thanks.
the hacky way:
def print_csv_data(data): open('my_output', 'w') f: f.write('program,version,count') k, v in data.iteritems(): id, count in v.iteritems(): f.write(k+','+id+','+count)
i'd recommend looking @ csv module though better use, above approach can break document if ids or program names contain commas.
import csv open('output.csv', 'w') csvfile: fieldnames = ['program', 'version', 'count'] writer = csv.dictwriter(csvfile, fieldnames=fieldnames) writer.writeheader() k, v in data.iteritems(): id, count in v.iteritems(): f.write({'program':k, 'version':id, 'count':count})
Comments
Post a Comment