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?

Asked By: CodingFrog

||

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.

Answered By: chepner

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
Answered By: Hunter Kohler
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.