ChainMap groups multiple mappings into a live view. Lookup runs from left to right, so command-line values can override environment settings and defaults without building another dictionary.

from collections import ChainMap

defaults = {"theme": "light", "timeout": 30}
environment = {"timeout": 10}
cli = {"theme": "dark"}

config = ChainMap(cli, environment, defaults)
print(config["theme"], config["timeout"])
config["debug"] = True  # writes to cli, the first mapping

How to use it safely

Writes and deletions affect only the first mapping. If you need an independent snapshot, merge dictionaries explicitly. Use new_child() to open a temporary scope and parents to return to the previous chain.

To strengthen the foundation, read Python collections guide and type hints guide.

The official Python documentation, accessed July 22, 2026, describes the API, edge cases, and version compatibility.