← Back to all snippets
PYTHON

Merge Multiple Dictionaries Efficiently

Discover how to merge several Python dictionaries into a single one using the dictionary unpacking operator (**) or `collections.ChainMap` for efficient and flexible dictionary combinations.

from collections import ChainMap

# Method 1: Using dictionary unpacking (**)
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict3 = {'d': 5}

merged_dict_unpack = {**dict1, **dict2, **dict3}
print(f"Merged with unpacking: {merged_dict_unpack}")

# Method 2: Using collections.ChainMap (for view and memory efficiency)
# ChainMap creates a single, updateable view of multiple mappings.
# Lookups search maps in the order they are given.
chain_map = ChainMap(dict3, dict2, dict1)
print(f"Merged with ChainMap (view): {chain_map}")

# Accessing values:
print(f"Value of 'b' in ChainMap: {chain_map['b']}") # Searches dict3, then dict2, then dict1

# Updating a dict in ChainMap reflects in the view
dict2['b'] = 99
print(f"ChainMap after dict2 update: {chain_map}")
How it works: This snippet demonstrates two powerful ways to merge multiple dictionaries in Python. The first method uses the dictionary unpacking operator `**` to create a new dictionary, combining all key-value pairs. If keys overlap, the value from the rightmost dictionary takes precedence. The second method utilizes `collections.ChainMap`, which creates a single logical view of multiple dictionaries without creating a new physical dictionary. This is memory-efficient for read-heavy scenarios, and lookups traverse the dictionaries in the order provided, with the first occurrence of a key being returned.

Need help integrating this into your project?

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

Hire DigitalCodeLabs