简体   繁体   English

Mypy:我应该如何输入一个以字符串为键且值可以是字符串或字符串列表的字典?

[英]Mypy: How should I type a dict that has strings as keys and the values can be either strings or lists of strings?

I am using Python 3.8.1 and mypy 0.782.我正在使用 Python 3.8.1 和 mypy 0.782。 I don't understand why mypy complains about the following code:我不明白为什么 mypy 抱怨以下代码:

from typing import Union, List, Dict
Mytype = Union[Dict[str, str], Dict[str, List[str]]]
s: Mytype = {"x": "y", "a": ["b"]}

Mypy gives the following error on line 3: Mypy 在第 3 行给出以下错误:

Incompatible types in assignment (expression has type "Dict[str, Sequence[str]]", variable has type "Union[Dict[str, str], Dict[str, List[str]]]")

If I change the last line to s: Mytype = {"a": ["b"]} mypy doesn't complain.如果我将最后一行更改为s: Mytype = {"a": ["b"]} mypy 不会抱怨。 However, when adding yet one more line s["a"].append("c") leads to an error:但是,当再添加一行时s["a"].append("c")会导致错误:

error: Item "str" of "Union[str, List[str]]" has no attribute "append"

How can the above mentioned be explained?上面提到的怎么解释? How should I type a dict that has strings as keys and the values can be either strings or lists of strings?我应该如何键入以字符串为键且值可以是字符串或字符串列表的字典?

Found this: https://github.com/python/mypy/issues/2984#issuecomment-285716826 but still not completely sure why the above mentioned happens and how should I fix it.发现这个: https://github.com/python/mypy/issues/2984#issuecomment-285716826但仍然不完全确定为什么会发生上述情况以及我应该如何解决它。

EDIT: Although it's still not clear why the suggested modification Mytype = Dict[str, Union[str, List[str]]] does not resolve the error with s['a'].append('c') I think the TypeDict approach suggested in the comments as well as in https://stackoverflow.com/a/62862029/692695 is the way to go, so marking that approach as a solution.编辑:虽然仍然不清楚为什么建议的修改Mytype = Dict[str, Union[str, List[str]]]不能解决错误s['a'].append('c')我认为 TypeDict评论中以及https://stackoverflow.com/a/62862029/692695中建议的方法是通往 go 的方法,因此将该方法标记为解决方案。

See similar question at: Indicating multiple value in a Dict[] for type hints , suggested in the comments by Georgy.请参阅类似问题: Indicating multiple value in a Dict[] for type hints ,Georgy 在评论中建议。

Because s: Mytype cannot have type Dict[str, str] and type Dict[str, List[str]] at the same time.因为s: Mytype不能同时具有类型Dict[str, str]和类型Dict[str, List[str]] You could do what you want like this:你可以像这样做你想做的事:

Mytype = Dict[str, Union[str, List[str]]]

But maybe problems, because Dict is invariant但也许有问题,因为Dict是不变的


Also you could useTypedDict , but only a fixed set of string keys is expected:您也可以使用TypedDict ,但只需要一组固定的字符串键:

from typing import List, TypedDict

MyType = TypedDict('MyType', {'x': str, 'a': List[str]})
s: MyType = {"x": "y", "a": ["b"]}

s['a'].append('c')

NOTE:笔记:

Unless you are on Python 3.8 or newer (where TypedDict is available in standard library typing module) you need to install typing_extensions using pip to use TypedDict除非您使用的是 Python 3.8 或更高版本(其中TypedDict在标准库类型模块中可用),否则您需要使用 pip 安装 typing_extensions 以使用 TypedDict


And, of course, you can use Any :而且,当然,您可以使用Any

Mytype = Dict[str, Any]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将字符串列表转换为dict,其中只有未知索引处的某种类型才能成为键? - How do I convert a list of strings into dict where only a certain type at an unknown index can become the keys? 转换为 dict/type 列表,一个包含字符串列表的字符串列表? - Convert to list of dict/type, a list of strings containing lists of strings? 如何同时按键和值对字典进行排序? 事实上,在我的字典中,键是字符串,我想按字母顺序排序,值是数字 - how to sort a dict by keys and values at the same time? in fact, in my dict, keys are strings and i want to sort alphabetically and values are number 如何将多个分隔位值列表组合成字符串? - How can I combine multiple lists of separated bit values into strings? 当键是字符串而值是列表时,如何填充 python 字典? - How to populate a python dictionary when keys are strings and values are lists? Python 使用字符串作为字典键 - Python using strings as dict keys 如何将字符串列表转换为键以给定 substring 开头的列表字典 - How to convert a list of strings to a dict of lists where keys start with given substring Python type hints: How to use Literal with strings to conform with mypy? - Python type hints: How to use Literal with strings to conform with mypy? 给定两个字符串列表,如何将它们转换为dict? - Given two list of strings, how can I convert them into a into a dict? 接受字符串或 (str, dict) 元组的列表 - Accepting a list either of strings or (str, dict) tuples
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM