简体   繁体   中英

Getting values from a dict according to a list of keys

I have a list.

mapper = {"a": 9, "b": 7}
A = ["a", "b"]

And I want to get:

result = [9, 7]

I know there are multiple ways to achieve that, like:

result = [mapper[char] for char in A]
result = list(map(lambda x: mapper[x], A))

For the second way, could we use operator module instead of using lambda?

I found a method called operator.getitem() ,and I try to use

result = list(map(operator.getitem(mapper), A))

But this will raise an exception.

I know list(map(lambda x: operator.getitem(mapper, x), A)) will work, but I just want to avoid using lambda .

I have found this question , but I didn't find a solution.

Looks like you're looking for operator.itemgetter (notice the second form, where it returns multiple items):

>>> operator.itemgetter(*A)(mapper)
(9, 7)

For completeness:

I find a method called operator.getitem() , and I try to use result = list(map(operator.getitem(mapper), A))

What went wrong here is that you want to pass mapper and one of the elements of A as two separate arguments each time - so you can't actually call the function in advance, but instead need to "bind" the mapper argument to the call.

For this, we use functools.partial :

import functools, operator

list(map(functools.partial(operator.getitem, mapper), A))

Awkward, but doable. This is why list comprehensions are much more Pythonic.

( operator.itemgetter can indeed do the whole thing in one shot as shown; but it's more commonly used when the element to access is fixed and the container varies - in particular, to sort a nested container by some key.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM