使用多种键值类型键入 Dict
typing Dict with multiple key value types
我有一个 python 函数,它 returns 具有以下结构的字典
{
(int, int): {string: {string: int, string: float}}
}
我想知道如何使用类型提示来指定它。所以,这些位很清楚:
Dict[Tuple[int, int], Dict[str, Dict[str, # what comes here]]
然而,内部字典有 int
和 float
两个键的值类型。我不确定如何注释
您应该可以使用 Union
:
Union type; Union[X, Y]
means either X or Y.
from typing import Union
Dict[Tuple[int, int], Dict[str, Dict[str, Union[int, float]]]
也就是说,如果密钥始终相同,则使用 tuple
或 namedtuple
代替内部 dict
可能是更好的主意。
我有一个 python 函数,它 returns 具有以下结构的字典
{
(int, int): {string: {string: int, string: float}}
}
我想知道如何使用类型提示来指定它。所以,这些位很清楚:
Dict[Tuple[int, int], Dict[str, Dict[str, # what comes here]]
然而,内部字典有 int
和 float
两个键的值类型。我不确定如何注释
您应该可以使用 Union
:
Union type;
Union[X, Y]
means either X or Y.
from typing import Union
Dict[Tuple[int, int], Dict[str, Dict[str, Union[int, float]]]
也就是说,如果密钥始终相同,则使用 tuple
或 namedtuple
代替内部 dict
可能是更好的主意。