Abdullah Tamimi
Abdullah Tamimi

Reputation: 97

Iteration to make a union of sets

I have a dictionary containing sets as the values, and I would like to make a union of all of these sets using a for loop. I have tried using set.union() with a for loop but I do not think this is working, any simple ways to do this iteration?

for key in self.thisDict.keys():
        for otherKey in self.thisDict.keys():
            if otherKey!=key:
                unionSet=set.union(self.thisDict[otherKey])

The problem I think I am having is that I am not making a union of all sets. I am dealing with a lot of data so it is hard to tell. With the unionSet object I am creating, I am printing out this data and it doesn't seem anywhere as large as I expect it to be

Upvotes: 2

Views: 4129

Answers (2)

L3viathan
L3viathan

Reputation: 27331

A simple set comprehension will do:

>>> d = {1: {1, 2, 3}, 2: {4, 5, 6}}
>>> {element for value in d.values() for element in value}
{1, 2, 3, 4, 5, 6}

To my eye, this is more readable:

>>> from itertools import chain
>>> set(chain.from_iterable(d.values()))
{1, 2, 3, 4, 5, 6}

Upvotes: 2

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23261

It's fairly naive approach - create a result set, iterate over dict values and update result set with values found in current iteration. |= is an alias for set.update method.

d = {1: {1, 2, 3}, 2: {4, 5, 6}}
result = set()
for v in d.values():
    result |= v

assert result == {1, 2, 3, 4, 5, 6}

Upvotes: 4

Related Questions