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.
zip() here to "pivot" the data! Nice!Basically the same thing but without using the csv module:
from __future__ import print_function
from collections import OrderedDict
data = OrderedDict()
data["p1"] = [.1, .2, .3, .4]
data["p2"] = [.4, .3, .2, .1]
data["p3"] = [.5, .6, .7, .8]
print(",".join(data.keys()))
print("\n".join(",".join(map(str, x)) for x in zip(*data.values())))
Output:
$ python -i foo.py
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
>>>
dict(s) have no defined order. You'll need to usecollections.OrderedDicthere to preserve the order.