开发者

Iterate through a dictionary and return results in a table

I`m looki开发者_如何学Pythonng at printing the content of a dictionary into a table, the dictionary is defined like this :

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

I would like to iterate through it to print row by row in the shell, the first row would contain the key, and the following rows, the content of tuple(date), tuple(open), etc ...


How about join the key onto the front of the tuple and then use zip(*) to transpose the result

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


Unless I'm misunderstanding:

for k in d:
    print k, '\t',
for v in d.values():
    print v, '\t',

Edit: Perhaps a better way:

print '\t'.join(d)
print '\t'.join(d.values())

Example:

d = {'apple':'green', 'lemon':'yellow', 'cherry':'red'}

Output:

cherry  lemon   apple
red     yellow  green


You could use Pandas (http://pandas.pydata.org/pandas-docs/stable/dsintro.html) , as long as the tuples are the same length you could do this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜