williamx
williamx

Reputation: 321

Get the dictionary values for every key in a list

Let's say I have a list:

a = ['apple', 'carrot']

and a dictionary:

d ={'apple': [2,4], 'carrot': [44,33], 'orange': [345,667]}

How can I use the list a as a key to lookup in the dictionary d? I want the result to be written to a comma-separated textfile like this

apple,    carrot
2,        44
4,        33

Corrected the a-list from a = ['apple', 'orange'] to a = ['apple', 'carrot']

Upvotes: 5

Views: 2068

Answers (3)

Arseniy
Arseniy

Reputation: 1778

Question is very old, but for future visitors I'd suggest using list comprehensions to get values of dict d for keys k in list a:

values = [ d[k] for k in a ]

Upvotes: 1

Daniel Stutzbach
Daniel Stutzbach

Reputation: 76727

a = ['apple', 'orange']
d ={'apple': [2,4], 'carrot': [44,33], 'orange': [345,667]}

print ',\t'.join(a)
for row in zip(*(d[key] for key in a)):
    print ',\t'.join(map(str, row))

Output:

apple,  orange
2,      345
4,      667

Upvotes: 8

Justin Peel
Justin Peel

Reputation: 47082

I know other people have been faster and their solutions are similar, but here's my take (take it or leave it):

a = ['apple', 'orange']

d ={'apple': [2,4], 'carrot': [44,33], 'orange': [345,667]}

fo = open('test.csv','w')
fo.write(',\t'.join(a)+'\n')
for y in xrange(len(d[a[0]])):
    fo.write(',\t'.join([str(d[i][y]) for i in a])+'\n')

fo.close()

which generates the file test.csv:

apple,  orange
2,      345
4,      667

Upvotes: 3

Related Questions