3

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

3 Answers 3

6

Use list comprehension:

>>> d = {'a':1, 'b':2 , 'c': 3}
>>> [d[k] for k in ['a','b']]
[1, 2]
Sign up to request clarification or add additional context in comments.

Comments

6

I would use map:

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

Comments

0

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

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

1 Comment

What if the dict had a key "bc"? This will only work if the dict has single character keys.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.