Dump a Python dictionary with array value inside to CSV -
i got this:
dict = {} dict["p1"] = [.1,.2,.3,.4] dict["p2"] = [.4,.3,.2,.1] dict["p3"] = [.5,.6,.7,.8]
how can dump dictionary csv structure? :
.1 .4 .5 .2 .3 .6 .3 .2 .7 .4 .1 .8
really appreciated !
dict
s have no order need ordereddict
, transpose values:
import csv collections import ordereddict d = ordereddict() d["p1"] = [.1,.2,.3,.4] d["p2"] = [.4,.3,.2,.1] d["p3"] = [.5,.6,.7,.8] open("out.csv","w") f: wr = csv.writer(f) wr.writerow(list(d)) wr.writerows(zip(*d.values()))
output:
p1,p2,p3 0.1,0.4,0.5 0.2,0.3,0.6 0.3,0.2,0.7 0.4,0.1,0.8
also best avoid shadowing builtin functions names dict
.
Comments
Post a Comment