Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Dict Typing vs Mapping: Which to Use

python dict typing vs mapping: Compare dict and Mapping in Python type hints: when each fits, how runtime behavior differs, and how the choice affects API design.

~4 min readPython
#python#type-hints#typing#mapping
Illustration comparing dict and Mapping type annotations in Python, showing a concrete dictionary object beside an abstract read-only mapping interface.

The choice between dict and Mapping in Python type hints is a practical decision that affects API flexibility, runtime behavior, and maintainability. It changes what callers may pass, what your function may do with the value, and how type checkers treat the annotation.

What dict and Mapping Actually Mean in Type Hints

dict is the concrete built-in dictionary type. When you annotate a parameter as dict[str, int], you are declaring that the argument should be a dict instance or a dict subclass. Mapping is an abstract type from collections.abc. It describes any object that supports the read-only mapping protocol — __getitem__, __len__, __iter__, and the related mixin methods — without requiring it to be a dict.

python
from collections.abc import Mapping def process(data: Mapping[str, int]) -> None: for key, value in data.items(): print(key, value)

This function accepts dict subclasses such as defaultdict and OrderedDict, other concrete mappings such as ChainMap, and any custom class that implements the mapping protocol.

Runtime Behavior: isinstance and Type Checking

The distinction matters if you perform runtime checks. isinstance(value, dict) returns False for a ChainMap or a custom mapping class. isinstance(value, Mapping) returns True for mapping implementations that inherit from or register with the ABC.

python
from collections import ChainMap from collections.abc import Mapping data = ChainMap() print(isinstance(data, dict)) # False print(isinstance(data, Mapping)) # True

This runtime difference matters when code validates inputs explicitly with isinstance. Type annotations themselves are not enforced by Python at runtime; type checkers use them for static analysis.

When to Annotate with dict

Use dict when the function needs the concrete dictionary type: for example, when it mutates a parameter by adding, removing, or updating keys, or when it constructs and returns a dictionary. If the function needs mutation but should accept any mutable mapping, use collections.abc.MutableMapping instead; choose dict when the API specifically requires a real dictionary.

python
def collect_counts(source: list[str]) -> dict[str, int]: counts: dict[str, int] = {} for word in source: counts[word] = counts.get(word, 0) + 1 return counts

Here the return type is dict because the function constructs and returns a new dictionary. Callers can rely on receiving a concrete dict with all its methods.

When to Annotate with Mapping

Use Mapping when the function only reads the data. This widens the accepted input types and signals that the function will not mutate the argument. It also makes testing easier: you can pass a simple mock or a custom read-only mapping without constructing a real dictionary.

python
from collections.abc import Mapping def render_config(config: Mapping[str, str]) -> str: return "\n".join(f"{k}={v}" for k, v in config.items())

This function never modifies config, so Mapping accurately describes its contract. A caller with a ChainMap or a custom mapping can pass it without type errors.

The Mutability Contract in API Design

The annotation communicates intent. Mapping tells the caller: "I will only read this." dict tells the caller: "I may modify this." This contract matters in larger codebases where a function's annotation is the primary documentation of its behavior.

python
def update_registry(registry: dict[str, int], key: str, value: int) -> None: registry[key] = value

If this function were annotated with Mapping, a type checker would flag the assignment, and at runtime it would raise TypeError for a read-only mapping implementation. The annotation must match the actual mutation behavior.

Common Pitfalls with dict vs Mapping

One common mistake is annotating a return value as Mapping when the function actually returns a dict. This is valid — a dict is a Mapping — but it hides the concrete type from callers. If callers need methods that Mapping does not expose, such as .setdefault() or .pop(), the annotation should be dict.

Another pitfall is using typing.Mapping instead of collections.abc.Mapping. typing.Mapping is a deprecated alias for collections.abc.Mapping; collections.abc is the recommended import.

python
from collections.abc import Mapping # preferred from typing import Mapping # deprecated alias

Performance and Overhead Considerations

The choice of annotation does not change how Python executes the function body. Annotations are not enforced at runtime, and unless code calls typing.get_type_hints(), an annotation is just an object stored in __annotations__. With from __future__ import annotations, annotations are stored as strings and are not evaluated until something such as get_type_hints() requests them.

The performance concern that remains is not the annotation but any explicit isinstance checks you add. isinstance(value, Mapping) may do more work than a direct dict type check, so the difference matters mainly in hot paths where the check runs millions of times.

The more significant design concern is that a Mapping annotation widens the accepted input types beyond dict objects. If your function relies on dict-specific ordering guarantees or on methods like .move_to_end(), the annotation must be dict or the function must explicitly convert the input.

Choosing Between dict and Mapping in Practice

The decision rule is straightforward: annotate with dict when the function mutates or constructs a dictionary, and with Mapping when the function only reads the input. For return types, prefer dict when the caller may need concrete dictionary methods, and Mapping when the caller should treat the result as read-only. If mutation is required but the input does not have to be a real dict, MutableMapping is the broader alternative.

python
from collections.abc import Mapping def merge(base: Mapping[str, int], extra: Mapping[str, int]) -> dict[str, int]: result = dict(base) result.update(extra) return result

This function accepts any mapping for input and returns a concrete dict, giving callers both flexibility and a predictable result type.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.