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:
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']]
c
:outer_keys = set()
inner_keys = set()
for x in c:
outer_keys.add(x[0])
inner_keys |= set(x[1:])
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
{'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}}
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}
{'dog': {'Okay': 0, 'Pl': 0, 'Good': 0, 'Bad': 0, 'Sg': 0},
'cat': {'Okay': 0, 'Pl': 0, 'Good': 0, 'Bad': 0, 'Sg': 0}}
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.
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}}