Search code examples
pythondictionarytypes

How to set the python type hinting for a dictionary variable?


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?


Solution

  • 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.