在Dict []中指示类型提示的多个值

Nij*_*jan 4 python dictionary

如何表达Dict具有两个不同类型值的两个键的类型?例如:

a = {'1': [], '2': {})
Run Code Online (Sandbox Code Playgroud)

以下只是为了让您了解我在寻找什么.

Dict [(str,List),(str,Set)]

ale*_*cxe 11

您要询问的功能称为"异构词典",您需要为特定键定义特定类型的值.这个问题目前正在讨论的类型与串钥匙异构词典尚未实现,仍然是开放的.目前的想法是使用所谓TypedDict的语法,如下所示:

class HeterogeneousDictionary(TypedDict):
    x: List
    y: Set
Run Code Online (Sandbox Code Playgroud)

请注意,mypy项目已通过"mypy extensions"(标记为试验性)提供此类型 - TypedDict:

from mypy_extensions import TypedDict

HeterogeneousDictionary = TypedDict('HeterogeneousDictionary', {'1': List, '2': Set})
Run Code Online (Sandbox Code Playgroud)

但至少,我们可以要求值为ListSet使用Union:

from typing import Dict, List, Set, Union

def f(a: Dict[str, Union[List, Set]]):
    pass
Run Code Online (Sandbox Code Playgroud)

当然,这并不理想,因为我们丢失了大量关于哪些键需要具有哪些类型值的信息.

  • [`TypedDict`](https://docs.python.org/3/library/typing.html#typing.TypedDict) 是在 Python 3.8 中添加的。答案应该更新。 (5认同)