2

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

Abdullah Tamimi
  • 97
  • 1
  • 2
  • 7

2 Answers2

4

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}
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
  • +1, this is the fastest of all proposed methods. Setup: `sampleSet = tuple(map(set,np.random.choice(1000000, (100,2000), replace = True))))` and then executing each of the 3 methods here gives 18.9 ms ± 353 µs for this one, 31.3 ms ± 1.96 for set comprehension and 27.2 ms ± 653 µs for the chain. – gt6989b Aug 02 '23 at 00:04
2

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}
L3viathan
  • 26,748
  • 2
  • 58
  • 81