将包含数组值的 Python 字典转储到 CSV



我得到了这样的东西:

dict = {}
dict["p1"] = [.1,.2,.3,.4]
dict["p2"] = [.4,.3,.2,.1]
dict["p3"] = [.5,.6,.7,.8] 

我怎样才能像这个结构一样把这个字典转储到csv中?

.1 .4 .5
.2 .3 .6
.3 .2 .7
.4 .1 .8

真的很感激!

dict没有

顺序,因此您需要一个OrderedDict并转置值:

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

输出:

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

基本上相同,但不使用 csv 模块:

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

输出:

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

最新更新