将嵌套 For 循环转换为字典推导式

问题描述 投票:0回答:2

我正在使用嵌套列表并尝试将嵌套 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:])

使用 for 循环创建字典:

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循环结果:

{'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 循环结果?键的顺序并不重要。

PEP 274 - 字典理解

python dictionary dictionary-comprehension nested-for-loop
2个回答
1
投票

您可以将

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}}

1
投票

只需根据您的内心字典创建一个新的

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}}
© www.soinside.com 2019 - 2024. All rights reserved.