← Back to all snippets
PYTHON

Combine Multiple Dictionaries into a Single Logical View with `ChainMap`

Discover how to use `collections.ChainMap` to efficiently combine several dictionaries, providing a single lookup interface without creating a new, merged dictionary.

from collections import ChainMap

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict3 = {'d': 5}

# Create a ChainMap from the dictionaries
combined_dict = ChainMap(dict1, dict2, dict3)

print(f"Combined ChainMap: {combined_dict}")
print(f"Value of 'a': {combined_dict['a']}") # Found in dict1
print(f"Value of 'c': {combined_dict['c']}") # Found in dict2
print(f"Value of 'b': {combined_dict['b']}") # Found in dict1 (first dictionary with 'b')

# Add a new key-value pair to the first dictionary
combined_dict['e'] = 6
print(f"Dict1 after modification: {dict1}")
print(f"Combined ChainMap after modification: {combined_dict}")
How it works: `collections.ChainMap` is a specialized dictionary class that groups multiple dictionaries together to create a single, updateable view. When performing a lookup, `ChainMap` searches each dictionary in the order they were provided until the key is found. Writes, deletions, and updates always operate on the first dictionary in the chain. This provides an efficient way to logically combine dictionaries without physically merging them into a new, single dictionary, which can be useful for managing configurations or scopes.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs