如何为字典的键和值指定类型提示?

How to specify type hints for dictionary key and values of a dict?

我有这样一本字典:

d = { 'my_label': ClassInstance() }

我想指定类型提示以指示键是字符串,值是 ClassInstance 的实例。

这在 Python 3.8 中可能吗?

我找到了 TypedDict 但这似乎试图指示一组固定的键。我允许任何字符串作为键。

使用Dict[K, V]:

from typing import Dict

d: Dict[str, ClassInstance] = { 'my_label': ClassInstance() }

是的,在 Python 3.8

中是可能的

首先导入字典类型提示:

from typing import Dict

并添加类型提示如下:

d: Dict[str, ClassInstance] = { 'my_label': ClassInstance() }

在 Python 3.9 中,可以在不从键入 (link to 3.9 documentation) as:

导入 Dict 的情况下执行此操作
d: dict[str, ClassInstance] = { 'my_label': ClassInstance() }