Course contentsShow
← Python
Lesson 556 of 1,0609. Type Safety and Code QualityFree lesson

Annotating Dictionaries with Key and Value Types

You will learn to define strict type constraints for dictionary keys and values to ensure consistent data structures throughout your application.

In this lesson, you will learn how to enforce strict type constraints on your dictionary keys and values to build more predictable and bug-resistant data structures.

Why Type-Annotate Dictionaries?

In Python, dictionaries are incredibly flexible, but that flexibility can lead to runtime errors if you accidentally insert an incorrect data type. While basic type hints allow you to mark a variable as a dict, explicit annotations tell your code editor and static analysis tools exactly what structure is expected. This ensures that you don't treat a string like an integer or inadvertently add a key that your logic isn't prepared to handle.

Defining Types with dict[K, V]

To annotate a dictionary, you use the dict type hint followed by square brackets containing two types: the first for the key and the second for the value.

# A dictionary where keys are strings and values are integers
scores: dict[str, int] = {
    "alice": 95,
    "bob": 82
}

# A dictionary where keys are integers (IDs) and values are strings (names)
user_registry: dict[int, str] = {
    101: "admin",
    102: "guest"
}

By providing these hints, tools like mypy or your IDE’s internal linter will flag errors if you attempt to assign an invalid type:

# This will trigger a type checking error:
scores["charlie"] = "excellent"  # Error: Value must be an int, not a str

Complex Dictionary Values

As your applications grow, you might need dictionaries where the values are more complex, such as lists or even other dictionaries. You can nest these annotations as needed:

# A dictionary where keys are strings and values are lists of floats
sensor_data: dict[str, list[float]] = {
    "temperature": [22.5, 23.0, 22.8],
    "humidity": [45.0, 46.2]
}

By defining these constraints, you turn your dictionaries from "black boxes" into well-defined contracts. This clarity not only helps you spot bugs during development but also makes your code significantly easier for other developers to read and maintain.

Key Takeaway: Use dict[KeyType, ValueType] to specify the expected types for keys and values, transforming dynamic dictionaries into robust, type-safe data structures.