Search code examples
pythondictionarysetdistinct-valuesunpack

Unpack values from nested dictionaries with depth level = 1


Is there a more elegant way to unpack values from nested dictionaries (depth level = 1) in a set?

d = {1: {10: 'a',
         11: 'b'},
     2: {20: 'a',
         21: 'c'}}


print(set(c for b in [[*set(a.values())] for a in d.values()] for c in b))
# {'a', 'b', 'c'}

Solution

  • You can iterate over values of nested dict and add in set.

    d = {1: {10: 'a',
             11: 'b'},
         2: {20: 'a',
             21: 'c'}}
    
    res = set(v for key,val in d.items() for v in val.values())
    
    print(res)
    # {'a', 'b', 'c'}