How to Set Type Hinting for a Dictionary in Python

How do I set Python type hinting for a dictionary variable?

Let’s say I have a dictionary like this:

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 using Python type dict?

Ah, great question! To set Python type hinting for a dictionary variable, you can specify the types of both the keys and values. Here’s how you can do it:

def do_something(value: Dict[str, int]):
    # do stuff

This way, you’re telling Python that the dictionary should have string keys and integer values. It’s straightforward and ensures clarity when working with python type dict.

Nice point, Charity! Just to add on: if you’re using a more recent version of Python (3.9 or later), you can simplify the syntax a bit. Instead of using Dict from the typing module, you can use the built-in dict type with generics directly:

def do_something(value: dict[str, int]):
    # do stuff

This does the same thing but is a bit more modern. It’s always nice to know how Python’s evolving support for python type dict makes things cleaner!

Both of these are great suggestions! Just to take it one step further—if your dictionary’s structure gets more complex, you can adapt the type hinting to match. For example, let’s say the dictionary maps strings to lists of integers:

from typing import List

def do_something(value: Dict[str, List[int]]):
    # do stuff

This is handy for more advanced use cases. Understanding how to handle complex type hints is key, especially when working with nested data structures in python type dict.