gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:53:50 37 4
gpt4 key购买 nike

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

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 中的子类型不会匹配(str, Dict[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]

关于python - Mypy 索引类型 "str"为 "Union[str, Dict[str, str]]"无效;预期类型 "Union[int, slice]",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69824126/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com