Search code examples
pythondictionarydictionary-comprehensionnested-for-loop

Converting Nested For-Loops to Dictionary Comprehensions


I am working with a nested list and attempting to convert a nested for-loop into a dictionary comprehension. Here's the code I'm starting with:

Minimal example of list of lists:

c = [['dog', 'Sg', 'Good'], ['cat', 'Pl', 'Okay'], ['dog', 'Pl', 'Bad'],
     ['dog', 'Sg', 'Good'], ['cat', 'Pl', 'Okay'], ['dog', 'Pl', 'Okay'],
     ['dog', 'Sg', 'Good'], ['cat', 'Sg', 'Good'], ['dog', 'Pl', 'Bad'],
     ['dog', 'Sg', 'Good'], ['cat', 'Pl', 'Okay'], ['dog', 'Pl', 'Bad']]

Creating sets of words from c:

outer_keys = set()
inner_keys = set()
for x in c:
    outer_keys.add(x[0])
    inner_keys |= set(x[1:])

Creating dictionary with for loop:

Lemma = dict()
for i in outer_keys:
    j_d = dict()
    for j in inner_keys:
        j_d[j] = 0
    j_d[i] = 0  # I am struggling to replicate this line with a dict comprehension
    Lemma[i] = j_d

For loop result:

{'dog': {'Okay': 0, 'Pl': 0, 'Good': 0, 'Bad': 0, 'Sg': 0, 'dog': 0},
 'cat': {'Okay': 0, 'Pl': 0, 'Good': 0, 'Bad': 0, 'Sg': 0, 'cat': 0}}

Attempting with dict comprehension:

I tried using a dict comprehension, but I couldn't incorporate i into the dictionary values for each key j.

Lemma = {j: {i: 0 for i in inner_keys} for j in outer_keys}

Result of my dict comprehension:

{'dog': {'Okay': 0, 'Pl': 0, 'Good': 0, 'Bad': 0, 'Sg': 0},
 'cat': {'Okay': 0, 'Pl': 0, 'Good': 0, 'Bad': 0, 'Sg': 0}}

Question:

How can I modify my dictionary comprehension so that it includes the outer key in the values, similar to the nested for-loop result? Order of keys does not matter.

PEP 274 - Dict Comprehensions


Solution

  • You can use dict.fromkeys together with inner_keys | {j}:

    >>> {j: dict.fromkeys(inner_keys | {j}, 0) for j in outer_keys}
    {'cat': {'Bad': 0, 'Good': 0, 'Okay': 0, 'Pl': 0, 'Sg': 0, 'cat': 0},
     'dog': {'Bad': 0, 'Good': 0, 'Okay': 0, 'Pl': 0, 'Sg': 0, 'dog': 0}}