Home > Software engineering >  How to get keys from the inner dictionaries of a nested dictionary using comprehension?
How to get keys from the inner dictionaries of a nested dictionary using comprehension?

Time:01-16

I am trying to find the keys of the dictionaries inside a dictionary and write them into a set using set/list comprehension.

So it looks like this:

dict_o_dicts = {
    1: {'de': 'eins', 'en': 'one' },
    2: {'de': 'zwei', 'en': 'two' },
    3: {'ru': 'три', 'gr': 'τρία' },
    0: {'ru': 'ноль' }}

I can get it working using:

result = set()
for x in dict_o_dicts:
    for y in dict_o_dicts[x]:
        result.add(y)

Gives the required output:

{'de', 'en', 'gr', 'ru'}

But I am required to solve it using a set/list comprehension. I tried everything, but I always get stuck somewhere. For example:

result = [set(dict_o_dicts[x].keys()) for x in dict_o_dicts]

It gives me a list of sets, but how could I unite them? I just don't know how to solve it in one line.

CodePudding user response:

Here is a short attempt (is this code golf? :p)

set().union(*dict_o_dicts.values())

output: {'de', 'en', 'gr', 'ru'}

CodePudding user response:

You can use double (or more) for loops in set (or other) comprehensions:

>>> { k for sub_dict in dict_o_dicts.values() for k in sub_dict }
{'de', 'gr', 'ru', 'en'}

CodePudding user response:

result = set()
[[result.add(y) for y in dict_o_dicts[x]] for x in dict_o_dicts]

You can do something like this.

The output:

{'ru', 'gr', 'en', 'de'}

CodePudding user response:

To do it with a single level comprehension, you could use unpacking with the set's union method:

set().union(*(v for v in dict_o_dicts.values()))

{'gr', 'ru', 'de', 'en'}

note that the comprehension is not actually required in this case

set().union(*dict_o_dicts.values())

{'gr', 'ru', 'de', 'en'}
  •  Tags:  
  • Related