Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dump a Python dictionary with array value inside to CSV

Tags:

python

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 !

like image 528
Yank Avatar asked Apr 27 '26 07:04

Yank


1 Answers

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.

like image 89
Padraic Cunningham Avatar answered Apr 28 '26 21:04

Padraic Cunningham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!