Fix Python – Dictionary: Get list of values for list of keys

Question

Asked By – FazJaxton

Is there a built-in/quick way to use a list of keys to a dictionary to get a list of corresponding items?

For instance I have:

>>> mydict = {'one': 1, 'two': 2, 'three': 3}
>>> mykeys = ['three', 'one']

How can I use mykeys to get the corresponding values in the dictionary as a list?

>>> mydict.WHAT_GOES_HERE(mykeys)
[3, 1]

Now we will see solution for issue: Dictionary: Get list of values for list of keys


Answer

A list comprehension seems to be a good way to do this:

>>> [mydict[x] for x in mykeys]
[3, 1]

This question is answered By – FazJaxton

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0