How to Set the Python Type Hinting for a Dictionary Variable?

Let say I have a dictionary stored in the variable 'v':

from typing import Dict

v = { 'height': 5, 'width':14, 'depth': 3 }

result = doSomething( v )

def doSomething( value:Dict[???] ):
    #do stuff

How do I declare the dictionary type in 'doSomething'? Any ideas anyone? Your help is much appreciated :)

3

2 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 doSomething(value: Dict[str, int]):

The documentation could probably be a little more explicit, though.

8

Update to answer due to new releases:

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
5
Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article