SchwarzbrotMitHummus
SchwarzbrotMitHummus

Reputation: 69

Using list comprehension to create nested dictionary with empty lists

I want to create a dictionary with dictionaries with empty lists inside. The nested dictionaries all have the same keys. I have a solution already; but I really don't think it is smart:

outer_keys = ['out_a', 'out_b', 'out_c']
inner_keys = ['in_a', 'in_b', 'in_c']
dictionary = {}
for o in outer_keys:
    dictionary[o] = {}
    for i in inner_keys:
        dictionary[o][i] = list()

This one works. The result is:

{'out_a': 
    {'in_a': [], 
     'in_b': [], 
     'in_c': []}, 
{'out_b': 
    {'in_a': [], 
     'in_b': [], 
     'in_c': []}, 
{'out_c': 
    {'in_a': [], 
     'in_b': [], 
     'in_c': []}}

But is there a way to do it in a single line?

I tried

dictionary = dict([(o, {i: list()}) for o in outer_keys for i in inner_keys])

which unfortunately only saves the last inner_key and leads to:

{'out_a': 
    {'in_c': []}, 
'out_b': 
    {'in_c': []}, 
'out_c': 
    {'in_c': []}}

Upvotes: 1

Views: 354

Answers (1)

Mureinik
Mureinik

Reputation: 311188

You can used a nested dict comprehension - the outer comprehension creates the dictionary, and for each key in it, another inner comprehension creates the inner dictionary

dictionary = {o: {i:list() for i in inner_keys} for o in outer_keys}

Upvotes: 1

Related Questions