2

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 !

4
  • Did you have tried anything so far? Commented Jun 13, 2015 at 14:29
  • I tried for key, val in result.items(): csv_writer.writerow([key,val]), however the data structure is not I want .. Commented Jun 13, 2015 at 14:29
  • 3
    Pleas add your code to question! Commented Jun 13, 2015 at 14:30
  • Python dict(s) have no defined order. You'll need to use collections.OrderedDict here to preserve the order. Commented Jun 13, 2015 at 14:33

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

4 Comments

amazing , works so good, after 5 mins later I will approve it .
I raelly like the use of zip() here to "pivot" the data! Nice!
@BhargavRao, indeed, added.
Now it looks even better :P
3

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
>>> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.