Reputation: 19466
I'm trying to do this:
list(map(lambda x: x.name, my_dict))
where my_dict
is a dict of form k, v
where v
is an object and v.name
is defined.
The problem is it is using the key k
for x
where I really want to use the value v
.
In other words: How do I map over the values of a dict?
PS I want to avoid my_dict[x]
as I will be using concurrent.futures
and won't be passing the full dict into separate threads.
Upvotes: 6
Views: 5043
Reputation: 23213
To retrieve view of values, you may use .values
method.
map(callable, my_dict.values())
Obviously, map
with trivial callables usually can be avoided in Python by using list or generator comprehensions.
[x.name for x in my_dict.values()] # creates list: non-lazy
(x.name for x in my_dict.values()) # creates generator: lazy
Upvotes: 6
Reputation: 107287
You don't need to use map()
and then convert the result to a list. Instead you can use simply use a list comprehension by looping over the dictionary values:
[v.name for v in my_dict.values()]
Or still if you are looking for a functional approach you can use attrgetter
function from operator module :
from operator import attrgetter
map(attrgetter('name'), my_dict.values())
Upvotes: 3