小编vhe*_*emt的帖子

mypy 和嵌套字典理解

我绝对不是 mypy 的专家,但有一个我真的不明白的错误。

假设我有这本字典,我想解析它并通过字典理解创建另一本字典。

my_dict = {
    'type1': {
        'category1': [
            'subcategory1',
            'subcategory2',
        ],
    },
    'type2': {
        'category2': [
            'subcategory3',
        ],
        'category3': [],
    },
}
Run Code Online (Sandbox Code Playgroud)

字典理解:

new_dict = {
    subcategory: {
        'category': category,
        'type': type,
    }
    for type, categories in my_dict.items()
    for category, subcategories in categories.items()
    for subcategory in subcategories
}
Run Code Online (Sandbox Code Playgroud)

和预期输出:

{
    'subcategory1': {
        'category': 'category1',
        'type': 'type1'
    },
    'subcategory2': {
        'category': 'category1',
        'type': 'type1'
    },
    'subcategory3': {
        'category': 'category2',
        'type': 'type2'
    }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,mypy 会因为空而抱怨category3,但会出现'error:"object" …

python list-comprehension dictionary-comprehension mypy

5
推荐指数
1
解决办法
5593
查看次数