Mypy "Union[str, Dict[str, str]]" 的无效索引类型 "str";预期类型 "Union[int, slice]"

Mypy Invalid index type "str" for "Union[str, Dict[str, str]]"; expected type "Union[int, slice]"

为什么我会收到错误消息?我已经正确添加了类型,对吗?

Invalid index type "str" for "Union[str, Dict[str, str]]"; expected type "Union[int, slice]"

代码

from typing import List, Dict, Union

d = {"1": 1, "2": 2}

listsOfDicts: List[Dict[str, Union[str, Dict[str, str]]]] = [
    {"a": "1", "b": {"c": "1"}},
    {"a": "2", "b": {"c": "2"}},
]

[d[i["b"]["c"]] for i in listsOfDicts]

Mypy 期望字典具有相同的类型。使用 Union 建模子类型关系,但由于 Dict 类型是不变的,因此键值对必须匹配 完全匹配 ,如类型注释中定义的那样——这是输入 Union[str, Dict[str, str]],因此 Union 中的子类型不会匹配(strDict[str, str] 都不是有效类型)。

要为不同的键定义多种类型,您应该使用TypedDict

此处显示的用法:https://mypy.readthedocs.io/en/latest/more_types.html#typeddict

from typing import List, Dict, Union, TypedDict

d = {"1": 1, "2": 2}

dictType = TypedDict('dictType', {'a': str, 'b': Dict[str, str]})

listsOfDicts: List[dictType] = [
    {"a": "1", "b": {"c": "1"}},
    {"a": "2", "b": {"c": "2"}},
]

[d[i["b"]["c"]] for i in listsOfDicts]