pythondictionarysetset-comprehension

Most efficient way to get values from a dictionary into a set


I cant seem to figure out how to write the following into a one line of code, using set comprehension. If its not possible is there a faster way to do what I am trying to do here? Basically just getting all the values of a dictionary into a set. Some values can be an empty set. A simple example is below

d = {1:set(),2:{1,2,3},3:{4}}

t = set()

for k, v in d.items():
   if len(v) > 0:
      t.update(v)

print(t)

output

{1,2,3,4}

Solution

  • Easiest is probably:

    >>> set.union(*d.values())
    {1, 2, 3, 4}
    

    There's no need to special-case an empty set in the values. Folding an empty set into the union makes no difference to the result, and checking for the length in advance in Python code is slower than just letting set.union() figure it out.

    WITH A SET COMPREHENSION

    You can do it with a set comprehension too, but I expect this way would be significantly slower (although I haven't timed it):

    >>> {x for oneset in d.values() for x in oneset}
    {1, 2, 3, 4}