Code Snippets
/

ChainMap for Layered Configs

ChainMap for Layered Configs

`collections.ChainMap` lets you stack multiple dicts and treat them as a single read-through view, with later dicts shadowing earlier ones. It is the right primitive for layered configs (defaults, environment, user overrides), nested scopes, and anywhere you would otherwise merge dicts repeatedly. This snippet covers the basic stacking, lookup-with-fallback semantics, and how new keys land in the first map by default.

Python
Medium
3 snippets
py-collections
py-standard-library
code-template
cheat-sheet

452 views

10

from collections import ChainMap

defaults = {'theme': 'light', 'lang': 'en', 'page_size': 20}
user = {'lang': 'fr', 'page_size': 50}
request = {'page_size': 100}

config = ChainMap(request, user, defaults)

print(config['theme'])      # 'light' (only in defaults)
print(config['lang'])       # 'fr' (user overrides defaults)
print(config['page_size'])  # 100 (request overrides everything)
print(list(config))         # all keys, deduplicated by first occurrence

ChainMap looks up keys by walking its maps in order, returning the first match. So ChainMap(request, user, defaults) reads as 'request takes priority, then user, then defaults'. This is the cleanest expression of layered configuration in the Python standard library. Iterating the chain returns each unique key exactly once, in first-occurrence order. The chain holds references to the underlying dicts (no copy), so updating any layer is immediately visible through the view.