[英]How do I convert a list of strings into dict where only a certain type at an unknown index can become the keys?
[英]Mypy: How should I type a dict that has strings as keys and the values can be either strings or lists of strings?
我正在使用 Python 3.8.1 和 mypy 0.782。 我不明白為什么 mypy 抱怨以下代碼:
from typing import Union, List, Dict
Mytype = Union[Dict[str, str], Dict[str, List[str]]]
s: Mytype = {"x": "y", "a": ["b"]}
Mypy 在第 3 行給出以下錯誤:
Incompatible types in assignment (expression has type "Dict[str, Sequence[str]]", variable has type "Union[Dict[str, str], Dict[str, List[str]]]")
如果我將最后一行更改為s: Mytype = {"a": ["b"]}
mypy 不會抱怨。 但是,當再添加一行時s["a"].append("c")
會導致錯誤:
error: Item "str" of "Union[str, List[str]]" has no attribute "append"
上面提到的怎么解釋? 我應該如何鍵入以字符串為鍵且值可以是字符串或字符串列表的字典?
發現這個: https://github.com/python/mypy/issues/2984#issuecomment-285716826但仍然不完全確定為什么會發生上述情況以及我應該如何解決它。
編輯:雖然仍然不清楚為什么建議的修改Mytype = Dict[str, Union[str, List[str]]]
不能解決錯誤s['a'].append('c')
我認為 TypeDict評論中以及https://stackoverflow.com/a/62862029/692695中建議的方法是通往 go 的方法,因此將該方法標記為解決方案。
請參閱類似問題: Indicating multiple value in a Dict[] for type hints ,Georgy 在評論中建議。
因為s: Mytype
不能同時具有類型Dict[str, str]
和類型Dict[str, List[str]]
。 你可以像這樣做你想做的事:
Mytype = Dict[str, Union[str, List[str]]]
但也許有問題,因為Dict
是不變的
您也可以使用TypedDict
,但只需要一組固定的字符串鍵:
from typing import List, TypedDict
MyType = TypedDict('MyType', {'x': str, 'a': List[str]})
s: MyType = {"x": "y", "a": ["b"]}
s['a'].append('c')
筆記:
除非您使用的是 Python 3.8 或更高版本(其中
TypedDict
在標准庫類型模塊中可用),否則您需要使用 pip 安裝 typing_extensions 以使用 TypedDict
而且,當然,您可以使用Any
:
Mytype = Dict[str, Any]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.