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]
Try This:
incase there are keys not in dict.
Following closure of Python: efficient way to create a list from dict values with a given order
Retrieving the keys without building the list:
The output:
Which matches the order given by the list
A little speed comparison:
So list comprehension and itemgetter are the fastest ways to do this.
UPDATE: For large random lists and maps I had a bit different results:
So in this case the clear winner is
f = operator.itemgetter(*l); f(m)
, and clear outsider:map(lambda _: m[_], l)
.UPDATE for Python 3.6.4:
So, results for Python 3.6.4 is almost the same.
A couple of other ways than list-comp:
map(mydict.__getitem__, mykeys)
None
if key not found:map(mydict.get, mykeys)
Alternatively, using
operator.itemgetter
can return a tuple:Note: in Python3,
map
returns an iterator rather than a list. Uselist(map(...))
for a list.