我正在考虑将字典的内容打印到表中,字典的定义如下:
d = {"date": tuple(date),"open":tuple(open),"close":tuple(close),"min":tuple(min),"max":tuple(max),"gain":tuple(gain),"loss":tuple(loss),"avg_gain":tuple(avg_gain),"avg_loss":tuple(avg_loss)}
我想迭代它以在shell中逐行打印,第一行包含键,以及以下行,元组(日期),元组(打开)等的内容...... / p>
答案 0 :(得分:6)
如何将密钥连接到元组的前面,然后使用zip(*)来转置结果
>>> d={"A":(1.0,2.0,3.0), "B":(4.0,5.0,6.0), "C":(7.0,8.0,9.0)}
>>> for row in zip(*([k]+map(str,v) for k,v in sorted(d.items()))):
... print "\t".join(row)
...
A B C
1.0 4.0 7.0
2.0 5.0 8.0
3.0 6.0 9.0
答案 1 :(得分:2)
除非我误解:
for k in d:
print k, '\t',
for v in d.values():
print v, '\t',
编辑:也许是一种更好的方式:
print '\t'.join(d)
print '\t'.join(d.values())
示例:
d = {'apple':'green', 'lemon':'yellow', 'cherry':'red'}
输出:
cherry lemon apple
red yellow green
答案 2 :(得分:0)
你可以使用Pandas(http://pandas.pydata.org/pandas-docs/stable/dsintro.html),只要元组的长度相同,你就可以这样做:
>>> import pandas
>>> d={"Green":(1,2,3,4), "Blue":(12,13,14,15), "Red":(1,3,5,7)}
>>> pandas.DataFrame(d)
Blue Green Red
0 12 1 1
1 13 2 3
2 14 3 5
3 15 4 7