Content · Programming · Python

Python collections.ChainMap: Combine Multiple Mappings

Read values from layered mappings with precedence.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Read values from layered mappings with precedence.

What You Will Learn


ChainMap searches mappings from first to last and writes or deletes only in the first mapping by default. Changes to underlying dictionaries remain visible.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

from collections import ChainMap
overrides = {'theme': 'dark'}
defaults = {'theme': 'light', 'language': 'en'}
settings = ChainMap(overrides, defaults)
print(settings['theme'])
print(settings['language'])

How the Example Works


  • The imports provide the standard-library tools used in the demonstration: collections.
  • The variable overrides holds the result of {'theme': 'dark'}. Later lines use that value or inspect how it changes.
  • The variable defaults holds the result of {'theme': 'light', 'language': 'en'}. Later lines use that value or inspect how it changes.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

Expected output from the example:

dark
en

When You Would Use This


Decide which input types are valid, what output should be produced, and which cases should fail clearly. A small self-contained demonstration is a good starting point before adding file access, network calls, or application state.

Practice: Modify the Code


Overlay user-specific settings onto defaults and inspect precedence.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Assuming writes to ChainMap automatically update the mapping where the key was found.
  • Assuming the operation has the same behavior for missing values, empty inputs and regular inputs.

Key Takeaways


  • Read values from layered mappings with precedence.
  • ChainMap searches mappings from first to last and writes or deletes only in the first mapping by default.
  • Apply this operation only after checking the assumptions and input conditions shown in the example.
Share this resourceSend this page to someone who may find it useful.