Home > Back-end >  Unpack values from nested dictionaries with depth level = 1
Unpack values from nested dictionaries with depth level = 1

Time:09-06

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'}

CodePudding user response:

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'}
  • Related