In this guide, you'll learn how to merge two and more dictionaries in Python using a single expression. Merging or concatenating dictionaries is a common task when combining data from multiple sources or configurations.

Quick Solutions

Here are the quickest ways to merge dictionaries:

(1) Using the merge operator (Python 3.9+)

merged = dict1 | dict2

(2) Using dictionary unpacking (Python 3.5+)

merged = {**dict1, **dict2}

(3) Using the update operator (Python 3.9+)

dict1 |= dict2  # Modifies dict1 in-place

Understanding Dictionary Merging

When merging dictionaries, if the same key appears in both dictionaries, the value from the second dictionary will overwrite the value from the first. Let's explore different methods with practical examples.

Method 1: Using the Merge Operator | (Python 3.9+)

The merge operator provides the cleanest and most readable syntax for combining dictionaries. It creates a new dictionary without modifying the originals.

# Sample dictionaries
dict1 = {'name': 'John', 'age': 30, 'city': 'New York'}
dict2 = {'age': 31, 'country': 'USA', 'occupation': 'Engineer'}

# Merge using | operator
merged = dict1 | dict2

print(merged)
# Output: {'name': 'John', 'age': 31, 'city': 'New York', 'country': 'USA', 'occupation': 'Engineer'}

Notice that the age value from dict2 (31) overwrites the value from dict1 (30). The merge operator returns a new dictionary, leaving both original dictionaries unchanged.

You can also merge multiple dictionaries at once:

dict1 = {'a': 1}
dict2 = {'b': 2}
dict3 = {'c': 3}

merged = dict1 | dict2 | dict3
print(merged)
# Output: {'a': 1, 'b': 2, 'c': 3}

Method 2: Using Dictionary Unpacking ** (Python 3.5+)

Dictionary unpacking with the double asterisk operator is compatible with older Python versions (3.5+) and provides similar functionality.

dict1 = {'name': 'Alice', 'role': 'Developer'}
dict2 = {'role': 'Senior Developer', 'team': 'Backend'}

# Merge using unpacking
merged = {**dict1, **dict2}

print(merged)
# Output: {'name': 'Alice', 'role': 'Senior Developer', 'team': 'Backend'}

This method creates a new dictionary by unpacking all key-value pairs from both dictionaries. Like the merge operator, values from the second dictionary take precedence for duplicate keys.

Merging multiple dictionaries:

config_defaults = {'timeout': 30, 'retries': 3}
config_user = {'timeout': 60}
config_override = {'debug': True}

final_config = {**config_defaults, **config_user, **config_override}
print(final_config)
# Output: {'timeout': 60, 'retries': 3, 'debug': True}

Method 3: Using the Update Operator |= (Python 3.9+)

If you want to merge dictionaries in-place (modifying the first dictionary), use the update operator:

dict1 = {'x': 1, 'y': 2}
dict2 = {'y': 3, 'z': 4}

# Merge in-place
dict1 |= dict2

print(dict1)
# Output: {'x': 1, 'y': 3, 'z': 4}

This modifies dict1 directly instead of creating a new dictionary, which can be more memory-efficient for large dictionaries.

Method 4: Using the update() Method

For Python versions below 3.5, or when you need to modify a dictionary in-place, use the update() method:

dict1 = {'product': 'Laptop', 'price': 1000}
dict2 = {'price': 1200, 'brand': 'Dell'}

# Update dict1 with dict2
dict1.update(dict2)

print(dict1)
# Output: {'product': 'Laptop', 'price': 1200, 'brand': 'Dell'}

While update() doesn't return a new dictionary, you can create a copy first if you need to preserve the original:

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

# Create a copy and update
merged = dict1.copy()
merged.update(dict2)

print(merged)
# Output: {'a': 1, 'b': 3, 'c': 4}
print(dict1)
# Output: {'a': 1, 'b': 2} - Original unchanged

Method 5: Using ChainMap (For Read-Only Views)

If you need a read-only view that chains multiple dictionaries without creating a new one, use ChainMap from the collections module:

from collections import ChainMap

dict1 = {'name': 'Bob', 'age': 25}
dict2 = {'age': 26, 'city': 'Boston'}

# Create a ChainMap
merged = ChainMap(dict1, dict2)

print(dict(merged))
# Output: {'age': 25, 'name': 'Bob', 'city': 'Boston'}

Note that ChainMap prioritizes the first dictionary for duplicate keys, opposite to other methods. It's particularly useful when you want to maintain separate dictionaries while providing a unified view.

Practical Examples

Example 1: Merging Configuration Settings

# Default settings
defaults = {
    'theme': 'light',
    'notifications': True,
    'language': 'en',
    'font_size': 12
}

# User preferences
user_prefs = {
    'theme': 'dark',
    'font_size': 14
}

# Merge with user preferences taking priority
settings = defaults | user_prefs
print(settings)
# Output: {'theme': 'dark', 'notifications': True, 'language': 'en', 'font_size': 14}

Example 2: Combining API Response Data

# Basic user info
user_info = {'id': 101, 'username': 'john_doe'}

# Profile details
profile = {'email': '[email protected]', 'verified': True}

# Activity stats
stats = {'posts': 42, 'followers': 150}

# Combine all data
user_complete = {**user_info, **profile, **stats}
print(user_complete)
# Output: {'id': 101, 'username': 'john_doe', 'email': '[email protected]', 'verified': True, 'posts': 42, 'followers': 150}

Example 3: Building Query Parameters

# Base parameters
base_params = {'format': 'json', 'limit': 10}

# Filter parameters
filters = {'category': 'technology', 'date': '2024-12'}

# Sort parameters
sort = {'sort_by': 'date', 'order': 'desc'}

# Combine all parameters
api_params = base_params | filters | sort
print(api_params)
# Output: {'format': 'json', 'limit': 10, 'category': 'technology', 'date': '2024-12', 'sort_by': 'date', 'order': 'desc'}

Choosing the Right Method

  • Use | operator (Python 3.9+) for the cleanest syntax when creating new dictionaries
  • Use ** unpacking (Python 3.5+) when you need compatibility with older Python versions
  • Use |= operator or update() when you want to modify a dictionary in-place
  • Use ChainMap when you need a read-only view or want to preserve original dictionaries

Key Takeaways

  • Dictionary merging combines key-value pairs from multiple dictionaries
  • For duplicate keys, the rightmost dictionary's value takes precedence (except with ChainMap)
  • Python 3.9+ offers the most concise syntax with the | and |= operators
  • Always consider whether you need a new dictionary or in-place modification
  • All methods handle duplicate keys automatically by overwriting with later values