Python Dictionary Type Hinting: From Dict to TypedDict

When working with dictionaries in Python, specifying the type of their keys and values makes your code easier to understand and maintain.

This tutorial will guide you through different ways to type hint dictionaries, starting from basic examples to more complex scenarios like dictionaries with specific structures and constraints.

 

 

Basic Dictionary Type Hinting

To hint at a simple dictionary, use the dict keyword along with types for keys and values.

from typing import Dict
age_dict: Dict[str, int] = {
    "Ahmed": 30,
    "Mona": 25,
    "Youssef": 40
}
print(age_dict)

Output:

{'Ahmed': 30, 'Mona': 25, 'Youssef': 40}

This dictionary maps names to ages, and the type hint ensures that all keys are strings, and all values are integers.

 

Type Hinting with Specific Key-Value Types

Use Dict to explicitly define the types for both keys and values.

from typing import Dict

# Mapping employee IDs (int) to salaries (float)
salary_dict: Dict[int, float] = {
    101: 4500.50,
    102: 5000.00,
    103: 6200.75
}

print(salary_dict)

Output:

{101: 4500.5, 102: 5000.0, 103: 6200.75}

Here, the type hints enforce that all keys are integers and all values are floating-point numbers.

 

Complex Type Hints

Nested dictionaries

Use nested Dict type hints for dictionaries containing other dictionaries.

from typing import Dict

# Department names mapped to dictionaries of employee names and their ages
department_dict: Dict[str, Dict[str, int]] = {
    "HR": {"Salma": 29, "Hassan": 35},
    "IT": {"Omar": 31, "Nour": 28}
}
print(department_dict)

Output:

{'HR': {'Salma': 29, 'Hassan': 35}, 'IT': {'Omar': 31, 'Nour': 28}}

This type hint defines a dictionary where the values are dictionaries themselves, with string keys and integer values.

Dictionaries with multiple possible value types (Union)

Use Union for dictionaries with mixed value types.

from typing import Dict, Union

# A dictionary mapping product names to price or stock count
product_dict: Dict[str, Union[float, int]] = {
    "Laptop": 999.99,
    "Mouse": 50,
    "Keyboard": 120.5
}
print(product_dict)

Output:

{'Laptop': 999.99, 'Mouse': 50, 'Keyboard': 120.5}

Each value in this dictionary can be either a float (price) or an integer (stock count).

 

Type Hinting Dictionaries of Objects

To type hint dictionaries containing instances of custom classes, use the class name.

from typing import Dict
class Employee:
    def __init__(self, name: str, position: str):
        self.name = name
        self.position = position
employee_dict: Dict[int, Employee] = {
    1: Employee("Khaled", "Manager"),
    2: Employee("Aya", "Developer")
}
for emp_id, emp in employee_dict.items():
    print(emp_id, emp.name, emp.position)

Output:

1 Khaled Manager
2 Aya Developer

The type hint ensures that values in the dictionary are Employee objects.

 

Type Hinting with Specific Structures

Use TypedDict to define a specific structure for dictionary entries.

from typing import TypedDict, Dict
class EmployeeInfo(TypedDict):
    name: str
    age: int
    department: str
employees: Dict[int, EmployeeInfo] = {
    1: {"name": "Hany", "age": 34, "department": "Finance"},
    2: {"name": "Laila", "age": 27, "department": "Marketing"}
}
print(employees)

Output:

{1: {'name': 'Hany', 'age': 34, 'department': 'Finance'}, 2: {'name': 'Laila', 'age': 27, 'department': 'Marketing'}}

This defines a specific structure for each dictionary value, enforcing the presence of certain fields and their types.

 

Type Hinting with Specific Key Constraints

To constrain the keys of a dictionary, you can use Literal.

from typing import Dict, Literal

# Dictionary with specific allowed keys
settings: Dict[Literal["theme", "language"], str] = {
    "theme": "dark",
    "language": "en"
}
print(settings)

Output:

{'theme': 'dark', 'language': 'en'}

The type hint ensures that only the keys "theme" and "language" are allowed.

 

Type Hinting Keys and Values Separately

Use KeysView and ValuesView from the typing module for separate key or value hints.

from typing import KeysView, ValuesView
data = {"Ali": 20, "Sara": 18, "Hassan": 21}
keys: KeysView[str] = data.keys()
values: ValuesView[int] = data.values()
print(keys, values)

Output:

dict_keys(['Ali', 'Sara', 'Hassan']) dict_values([20, 18, 21])

This ensures that the keys are strings and the values are integers.

 

Type Hinting Dictionaries of Collections

Use collection types as dictionary values.

from typing import Dict, List
project_teams: Dict[str, List[str]] = {
    "ProjectA": ["Hesham", "Dina", "Farah"],
    "ProjectB": ["Samir", "Nadia"]
}
print(project_teams)

Output:

{'ProjectA': ['Hesham', 'Dina', 'Farah'], 'ProjectB': ['Samir', 'Nadia']}
Leave a Reply

Your email address will not be published. Required fields are marked *