Sling Academy
Home/Python/Python: Using type hints with dictionaries

Python: Using type hints with dictionaries

Last updated: February 13, 2024

Introduction

In the world of Python development, enhancing code readability and reducing the chances of bugs are paramount. Type hints with dictionaries are a powerful feature introduced in Python 3.5 to address these concerns, offering a more explicit syntax for variable types.

Using Type Hints with Dicts

Before diving into dictionaries, let’s understand what type hints are. Introduced in PEP 484, type hints allow developers to indicate the expected data type of a function’s parameters, return values, and variables. This doesn’t change Python’s dynamic nature but supports better IDE integrations and static code analysis through tools like Mypy.

Basic Examples

For our first foray into using type hints with dictionaries, we’ll start with a simple example. Assume you have a dictionary that maps employee IDs (as integers) to their names (as strings).

employee: dict[int, str] = {1: "John", 2: "Doe"}
print(employee)

Output:

{1: 'John', 2: 'Doe'}

This code snippet clearly shows the expected key-value pairs within the dictionary, enhancing readability and type safety.

Advancing with Type Hints

Moving on to a slightly more advanced example, let’s see how we can specify dictionaries that contain other dictionaries as values, to store more complex data structures.

departments: dict[str, dict[int, str]] = {
  "Engineering": {1: "John Doe"},
  "Marketing": {2: "Jane Doe"}
}
print(departments)

Output:

{'Engineering': {1: 'John Doe'}, 'Marketing': {2: 'Jane Doe'}}

This example highlights the ability to nest dictionaries and explicitly define their structure using type hints, making the code more maintainable and understandable.

Using TypedDict for More Clarity

When dictionaries have a fixed structure, TypedDict becomes immensely helpful. Available from Python 3.8 as part of the typing module, it allows specifying dictionary keys and their corresponding types in a clear and concise manner.

from typing import TypedDict

class Employee(TypedDict):
    id: int
    name: str
    department: str

employee: Employee = {'id': 1, 'name': 'John Smith', 'department': 'Engineering'}
print(employee)

Output:

{'id': 1, 'name': 'John Smith', 'department': 'Engineering'}

This example shows how TypedDict enhances the specificity and readability of type hints for dictionaries with a consistent structure.

Working with Generics and TypeVars

For more complex scenarios where dictionary structures are not fixed, Python’s generics and TypeVar can provide flexible solutions. Here, we can define a type hint that allows dictionaries with keys of any type but enforces the values to be of a specific type.

from typing import TypeVar, Dict

V = TypeVar('V')
def function(dict_: Dict[any, V]) -> V:
  # implementation

This approach, while advanced, gives developers the freedom to define more abstract data types and leverage strong typing in dynamic and complex data structures.

Conclusion

Type hints have become an essential part of Python code, particularly when working with structures as versatile as dictionaries. They not only help in making the code more readable but also significantly enhance its maintainability. By understanding and utilizing the various methods of typing dictionaries, from basic examples to employing TypedDict and generics, developers can ensure their code is robust, clear, and bug-resistant.

Next Article: Python: How to get the length of a dictionary

Previous Article: How to update a nested dictionary in Python (basic and advanced)

Series: Working with Dict, Set, and Tuple in Python

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types