CodeKingPlusPlus CodeKingPlusPlus - 8 months ago 51
Python Question

python reduce to find the union of sets

I am trying to find the union of set of sets. Specifically I want the union of the list of nodes for each key in the dictionary of

graphs called
. I would like to use the
function as it seems reasonable to take the union of all
is a key of

Here is my attempt:

reduce(lambda x,y: set(periodic_gs[x].nodes()).union(set(periodic_gs[y].nodes())), periodic_gs.keys(), {})

To me, this says take the union of the nodes across each graph in the dictionary. For some reason, python tells me:
TypeError: unhashable type: 'dict'
I do not see this
, because
is a list of the keys (they are strings but I do not see how this would matter), and when substituted in for the arguments to the lambda function will work.

What is causing the type error and how do I fix it?


You can use set.union like this:

>>> lis = [{1, 2, 3, 4}, {3, 4, 5}, {7, 3, 6}]
>>> set().union(*lis)
set([1, 2, 3, 4, 5, 6, 7])

Using reduce:

>>> reduce(set.union, lis)
set([1, 2, 3, 4, 5, 6, 7])

For your code this should do it:

set().union(*(x.nodes() for x in periodic_gs.values()))
reduce(set.union, (x.nodes() for x in periodic_gs.values()))