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

Viewed 1455

I have a dictionary like so:

d = { 'my_label': ClassInstance() }

I would like to specify type hints to indicate that keys are strings, and values are instances of ClassInstance.

Is this possible in Python 3.8?

I found TypedDict but that seems to attempt to indicate a fixed set of keys. I would to allow any string as key.

2 Answers

Yes, it is possible in Python 3.8

First import dictionary type hint:

from typing import Dict

and add type hint as following:

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

In Python 3.9, it is possible to do this without importing Dict from typing (link to 3.9 documentation) as:

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

Use Dict[K, V]:

from typing import Dict

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