How to set the python type hinting for a dictionary variable?
Question:
Let say I have a dictionary:
from typing import Dict
v = { 'height': 5, 'width': 14, 'depth': 3 }
result = do_something(v)
def do_something(value: Dict[???]):
# do stuff
How do I declare the dictionary type in do_something
?
Answers:
Dict
takes two "arguments", the type of its keys and the type of its values. For a dict
that maps strings to integers, use
def do_something(value: Dict[str, int]):
The documentation could probably be a little more explicit, though.
Python 3.9 on:
Use lowercase dict
in the same method as the accepted answer. typing.Dict
and similar upper case generic types which mirror built-ins are deprecated due to PEP 585:
def my_func(value: dict[str, int]):
pass
Let say I have a dictionary:
from typing import Dict
v = { 'height': 5, 'width': 14, 'depth': 3 }
result = do_something(v)
def do_something(value: Dict[???]):
# do stuff
How do I declare the dictionary type in do_something
?
Dict
takes two "arguments", the type of its keys and the type of its values. For a dict
that maps strings to integers, use
def do_something(value: Dict[str, int]):
The documentation could probably be a little more explicit, though.
Python 3.9 on:
Use lowercase dict
in the same method as the accepted answer. typing.Dict
and similar upper case generic types which mirror built-ins are deprecated due to PEP 585:
def my_func(value: dict[str, int]):
pass