【发布时间】:2021-11-03 11:34:36
【问题描述】:
为什么我会收到错误消息?我已经正确添加了类型,对吧?
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]
【问题讨论】:
-
[d[i["b"]["c"]] for i in listsOfDicts if isinstance(i["b"], dict)]
-
@alex_noname 你能解释一下永远为真的 if 条件(在我的情况下)如何消除错误吗?
标签: python mypy python-typing