Finger twist
Finger twist

Reputation: 3786

Iterate through a dictionary and return results in a table

I`m looking 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 ...

Upvotes: 2

Views: 3519

Answers (3)

sk8asd123
sk8asd123

Reputation: 1705

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

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304355

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

Upvotes: 6

Steve Tjoa
Steve Tjoa

Reputation: 61074

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

Upvotes: 2

Related Questions