小编zna*_*f94的帖子

带有键/值类型对的类型提示字典

是否可以使用 Python 类型提示将字典的键和值的类型指定为对?

例如 :

  • 如果键是 an int,则值应该是 astr
  • 如果 key 是 a str,value 应该是 anint

如果我写:

Dict[Union[int, str], Union[int, str]]
Run Code Online (Sandbox Code Playgroud)

它允许str -> strint -> int,这是不允许的。

与 :

Union[Dict[int, str], Dict[str, int]]
Run Code Online (Sandbox Code Playgroud)

字典可以是aDict[int, str]Dict[str, int]但不能同时是两者......

我也研究过TypedDict,但它需要明确给出所有密钥。

python dictionary type-hinting python-3.x

5
推荐指数
1
解决办法
5104
查看次数

标签 统计

dictionary ×1

python ×1

python-3.x ×1

type-hinting ×1