python - How to save Multi-layered dictionary to csv -
python - How to save Multi-layered dictionary to csv -
i have 3 layed dictionary need save in csv format. followed code in post. 2 rows info dumped in 1 row.
how can separate info , write them separate cells.
{'alpha': {'2010': {'216': 0.0, '217': 0.0, '218': 195.37308756510416}}}
there other keys (beta
, omega
) @ same level alpha
.
i'd final product like:
alpha,2010,216,0.0 alpha,2010,217,0.0 alpha,2010,218,195.37308756510416 ..... beta, .....
and preferably save in .csv
file, text file too.
this code have tried.
with open('mycsvfile.csv', 'wb') f: w = csv.dictwriter(f, datadictionary.keys()) w.writeheader() w.writerow(datadictionary)
thanks
first, suggestion: if you're going post info you're processing, omit little representative sample - ain't nobody got time ready through numbers scrolling off border of screen.
here's smaller sample of input:
{'alpha': {'2010': {'216': 0.0, '217': 0.0, '218': 195.4 } } }
one of things don't state whether there other keys @ same level 'alpha' , 1 time again @ level of '2010'. if so, csv going have include values in each row also.
here's suggested csv format, column headers:
section,year,key,value alpha,2010,216,0.0 alpha,2010,217,0.0 alpha,2010,218,195.37308756510416 ... etc.
so how create this?
just iterate through dictionaries, , maintain track of outer dictionary keys insert in each row:
text = "section,year,key,value\n" sectionname in mydata: yeardata = mydata[sectionname] year in yeardata: keyvaluedict = yeardata[year] key in keyvaluedict: value = keyvaluedict[key] text += sectionname + "," + year + "," + key + "," + str(value) + "\n"
to write csv file:
f = open("mydata.csv", "w") f.write(text) f.close()
python csv
Comments
Post a Comment