I’m trying to use map() on the dict_values object returned by the values() function on a dictionary. However, I can’t seem to be able to map() over a dict_values:
map(print, h.values())
Out[31]: <builtins.map at 0x1ce1290>
I’m sure there’s an easy way to do this. What I’m actually trying to do is create a set() of all the Counter keys in a dictionary of Counters, doing something like this:
# counters is a dict with Counters as values
whole_set = set()
map(lambda x: whole_set.update(set(x)), counters.values())
Is there a better way to do this in Python?
In Python 3,
mapreturns an iterator, not a list. You still have to iterate over it, either by callingliston it explicitly, or by putting it in aforloop. But you shouldn’t usemapthis way anyway.mapis really for collecting return values into an iterable or sequence. Since neitherprintnorset.updatereturns a value, usingmapin this case isn’t idiomatic.Your goal is to put all the keys in all the counters in
countersinto a single set. One way to do that is to use a nested generator expression:There’s also the lovely dict comprehension syntax, which is available in Python 2.7 and higher (thanks Lattyware!) and can generate sets as well as dictionaries:
These are both roughly equivalent to the following: