Meaning of the word python map ()

I am trying to use map()for an object dict_valuesreturned by a function values()in a dictionary. However, I cannot possibly map()use:

map(print, h.values())
Out[31]: <builtins.map at 0x1ce1290>

I am sure there is an easy way to do this. What I'm actually trying to do is create set()all the keys Counterin the dictionary 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?

+5
source share
2 answers

Python 3, map , . , list, for. map. map . print, set.update , map .

- counters . - :

s = set(key for counter in counters.values() for key in counter)

, Python 2.7 ( Lattyware!) , :

s = {key for counter in counters.values() for key in counter}

:

s = set()
for counter in counters.values():
    for key in counter:
        s.add(key)
+13

counters? .

counters[1].union(counters[2]).union(...).union(counters[n])

? functools.reduce:

import functools

s = functools.reduce(set.union, counters.values())


counters.values() (, ), . , dict-, iteritems, :

>>> counters = {1:[1,2,3], 2:[4], 3:[5,6]}
>>> counters = {k:set(v) for (k,v) in counters.iteritems()}
>>> print counters
{1: set([1, 2, 3]), 2: set([4]), 3: set([5, 6])}

, , inline, counters.keys():

>>> counters = {1:[1,2,3], 2:[4], 3:[5,6]}
>>> functools.reduce(set.union, [set(v) for v in counters.values()])
set([1, 2, 3, 4, 5, 6])
0

All Articles