I got something like this:
dict = {}
dict["p1"] = [.1,.2,.3,.4]
dict["p2"] = [.4,.3,.2,.1]
dict["p3"] = [.5,.6,.7,.8]
How I can dump this dictionary into csv like this structure? :
.1 .4 .5
.2 .3 .6
.3 .2 .7
.4 .1 .8
Really appreciated !
dicts have no order so you would need an OrderedDict and to transpose the values:
import csv
from collections import OrderedDict
d = OrderedDict()
d["p1"] = [.1,.2,.3,.4]
d["p2"] = [.4,.3,.2,.1]
d["p3"] = [.5,.6,.7,.8]
with open("out.csv","w") as 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 to avoid shadowing builtin functions names like dict.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With