python - 使用嵌套 for 循环的推导式创建字典

标签 python python-3.x dictionary list-comprehension

我有一个嵌套的 for 循环,在其中设置新字典的键、值。了解列表推导式后,我想知道是否可以对字典使用相同的逻辑。

我对字典的一行理解的尝试目前失败了:

dict_contract_name_id = {each_contract: each_contract.id for each_inuring_layer in context.program_obj.inuringLayers for each_contract in each_inuring_layer.contracts}

它失败了,并显示TypeError: unhashable type: 'ContractWithId'

我试图转换为一行理解的实际代码:

dict_contract_name_id = {}
for each_inuring_layer in context.program_obj.inuringLayers:
    for each_contract in each_inuring_layer.contracts:
        if each_contract.name in contracts:
            dict_contract_name_id[each_contract.name] = each_contract.id

最佳答案

您忘记了 .name 属性以及 if 过滤器:

dict_contract_name_id = {
    each_contract.name: each_contract.id
    for each_inuring_layer in context.program_obj.inuringLayers
    for each_contract in each_inuring_layer.contracts
    if each_contract.name in contracts}

您尝试使用 each_contract 对象作为键,而不仅仅是名称。

关于python - 使用嵌套 for 循环的推导式创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35625010/

相关文章:

python - 从配置文件 Python 中读取值

python - 梯度下降实现python——轮廓线

python - 通过将背景设为白色来从背景中提取前景

python - 仅更改具有多个值的字典中键的一个值

python - 为什么 python timeit 结果与 shell 的时间命令相矛盾?

python - 如何使用 selenium/python 获取父 web 元素下的所有 xml/dom 作为文本?

Python MySQL 连接器未插入

arrays - Swift:将二维数组转换为自定义对象数组

bash - unix map 功能

python-3.x - 如果发送的消息是带有 TELETHON 的 Telegram 中的位置共享消息,我可以获取该位置的经度和纬度吗