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...
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 :)
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.
Update to answer due to new releases:
Must Read
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