Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map over a dict

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.

like image 778
cjm2671 Avatar asked Jul 28 '16 13:07

cjm2671


1 Answers

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
like image 54
Łukasz Rogalski Avatar answered Oct 02 '22 14:10

Łukasz Rogalski