JuanPablo
JuanPablo

Reputation: 24834

Get values in Python dictionary from list of keys

If I have a dictionary

d = {'a':1, 'b':2 , 'c': 3}

with d['a'] or d.get('a') I get 1.

How can I get the values in the dictionary from a list of keys?

Something like

d[['a','b']]

Upvotes: 3

Views: 185

Answers (3)

hendrik
hendrik

Reputation: 2042

Alternatively to a list in this case you could use a string. Like so:

map({'a':1, 'b':2 , 'c': 3}.get,"abc")

Upvotes: 0

arshajii
arshajii

Reputation: 129572

I would use map:

>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> map(d.get, ['a','b'])
[1, 2]

Upvotes: 6

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251186

Use list comprehension:

>>> d = {'a':1, 'b':2 , 'c': 3}
>>> [d[k] for k in ['a','b']]
[1, 2]

Upvotes: 6

Related Questions