我正在使用嵌套列表并尝试将嵌套 for 循环转换为字典理解。这是我开始的代码:
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
合并到每个键 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}}
如何修改我的字典理解,使其在值中包含外键,类似于嵌套的 for 循环结果?键的顺序并不重要。
您可以将
dict.fromkeys
与 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}}
只需根据您的内心字典创建一个新的
dict
>>> {j: dict({i: 0 for i in inner_keys}, **{j:0}) for j in outer_keys}
{'dog': {'Bad': 0, 'Good': 0, 'Okay': 0, 'Sg': 0, 'dog': 0, 'Pl': 0}, 'cat': {'Bad': 0, 'Good': 0, 'Okay': 0, 'Sg': 0, 'Pl': 0, 'cat': 0}}