3

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.

5 Answers5

4

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

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

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

mozway
  • 194,879
  • 13
  • 39
  • 75
3

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'}
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • 1
    you can replace set() syntax with {} so you have a nested set comprehension. what currently it is using looks like a gen expression and a set() constructor, which is not ideal. – rv.kvetch Jan 15 '22 at 16:29
0
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'}
Bemwa Malak
  • 1,182
  • 1
  • 5
  • 18
0

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'}
Alain T.
  • 40,517
  • 4
  • 31
  • 51
0

To extract all possible keys from a nested dict of any depth try this recursive function:

def get_all_keys(d):
    res=[]
    for k, v in d.items():
        if type(v) == dict: 
            # comment this line if you need only last level
            res.append(k)
            res = res + get_all_keys(v)
        else: res.append(k)
    return res