How do I merge two dictionaries in a single expression in Python?
I want to merge two dictionaries into a new dictionary. For example:
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = merge(x, y)
>>> z
{'a': 1, 'b': 3, 'c': 4}
Whenever a key k is present in both dictionaries, only the value y[k] should be kept.
The most straightforward way to merge two dictionaries in a single expression in Python is to use the dictionary unpacking syntax {**dict1, **dict2}, which creates a new dictionary containing all key-value pairs from both dictionaries, with values from the second dictionary taking precedence for duplicate keys. This approach is available in Python 3.5 and later and provides a clean, readable one-line solution that doesn’t modify the original dictionaries.
Contents
- Dictionary Unpacking Method
- Dictionary Union Operator (Python 3.9+)
- Alternative Methods for Older Python Versions
- Practical Examples and Use Cases
- Performance and Best Practices
- Common Issues and Solutions
Dictionary Unpacking Method
The dictionary unpacking operator ** introduced in Python 3.5 provides the most elegant and widely used approach for merging dictionaries in a single expression. This method creates a new dictionary by unpacking all key-value pairs from both source dictionaries.
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}
print(z) # Output: {'a': 1, 'b': 3, 'c': 4}
How it works: The {**x, **y} syntax creates a new dictionary and first unpacks all items from x, then unpacks all items from y. When duplicate keys exist, the value from the later unpacked dictionary (in this case y) overwrites the value from the earlier one.
As PythonHow explains, “This creates a new dictionary and unpacks all (key-value) pairs into the new dictionary.”
Key advantages:
- Creates a new dictionary without modifying the originals
- Readable and concise syntax
- Works with any number of dictionaries
- Available in Python 3.5+
Dictionary Union Operator (Python 3.9+)
Python 3.9 introduced the pipe operator | as the official dictionary union operator, providing an even more concise syntax for merging dictionaries:
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = x | y
print(z) # Output: {'a': 1, 'b': 3, 'c': 4}
This operator follows the same behavior as dictionary unpacking, where duplicate keys are resolved by taking the value from the right-hand dictionary. The union operator also supports the in-place version |= for modifying a dictionary:
x = {'a': 1, 'b': 2}
x |= {'b': 3, 'c': 4}
print(x) # Output: {'a': 1, 'b': 3, 'c': 4}
According to SparkByExamples, these methods provide “multiple ways to achieve this” dictionary merging functionality.
Alternative Methods for Older Python Versions
For Python versions before 3.5, or when working with code that needs to support older versions, several alternative approaches are available.
Using the update() Method
The update() method modifies the first dictionary in place. To preserve the original dictionaries, you can create a copy first:
import copy
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
# Create a copy and update it
z = copy.copy(x)
z.update(y)
print(z) # Output: {'a': 1, 'b': 3, 'c': 4}
Dictionary Comprehension
You can use dictionary comprehension to merge dictionaries:
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {k: y.get(k, x.get(k)) for k in set(x) | set(y)}
print(z) # Output: {'a': 1, 'b': 3, 'c': 4}
Custom Function for Backward Compatibility
As suggested on Stack Overflow, you can create a reusable function:
def merge_two_dicts(x, y):
"""Given two dictionaries, merge them into a new dict as a shallow copy."""
z = x.copy() # Start with x's keys and values
z.update(y) # Modify z with y's keys and values
return z
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = merge_two_dicts(x, y)
print(z) # Output: {'a': 1, 'b': 3, 'c': 4}
Practical Examples and Use Cases
Merging Multiple Dictionaries
The dictionary unpacking method easily extends to merging more than two dictionaries:
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict3 = {'c': 5, 'd': 6}
# Merge three dictionaries
merged = {**dict1, **dict2, **dict3}
print(merged) # Output: {'a': 1, 'b': 3, 'c': 5, 'd': 6}
Merging with Default Values
You can merge dictionaries while providing default values for missing keys:
defaults = {'color': 'blue', 'size': 'medium'}
user_settings = {'size': 'large', 'material': 'cotton'}
# Merge with defaults (user settings take precedence)
final_settings = {**defaults, **user_settings}
print(final_settings) # Output: {'color': 'blue', 'size': 'large', 'material': 'cotton'}
Dynamic Dictionary Merging
You can dynamically merge dictionaries stored in a list or tuple:
dicts = [{'a': 1, 'b': 2}, {'b': 3, 'c': 4}, {'c': 5, 'd': 6}]
# Merge all dictionaries in the list
merged = {}
for d in dicts:
merged = {**merged, **d}
print(merged) # Output: {'a': 1, 'b': 5, 'c': 5, 'd': 6}
Performance and Best Practices
Performance Comparison
The different merging methods have varying performance characteristics:
| Method | Time Complexity | Space Complexity | Modifies Original | Python Version |
|---|---|---|---|---|
{**x, **y} |
O(n + m) | O(n + m) | No | 3.5+ |
| `x | y` | O(n + m) | O(n + m) | No |
x.update(y) |
O(m) | O(1) | Yes | All |
| Dictionary comprehension | O(n + m) | O(n + m) | No | All |
Best Practices
-
Use dictionary unpacking for readability: The
{**x, **y}syntax is generally the most readable and Pythonic approach for modern Python versions. -
Consider Python version compatibility: If your code needs to support older Python versions, use the custom function approach or check for Python version compatibility.
-
Be aware of shallow copying: All these methods perform shallow copying. If your dictionaries contain mutable objects as values, changes to those objects will affect the merged dictionary.
-
Use union operator for cleanest syntax: If you’re using Python 3.9+, the
|operator provides the cleanest syntax.
As Be on the Right Side of Change notes, “The dictionary unpacking feature z = {**dict1, **dict2} creates a new dictionary and unpacks all (key-value) pairs into the new dictionary.”
Common Issues and Solutions
Handling Non-String Keys
Dictionary unpacking works with any hashable key types, not just strings:
x = {1: 'one', 2: 'two'}
y = {2: 'dos', 3: 'tres'}
z = {**x, **y}
print(z) # Output: {1: 'one', 2: 'dos', 3: 'tres'}
Nested Dictionary Merging
For nested dictionaries, you’ll need a recursive approach:
def deep_merge(dict1, dict2):
result = dict1.copy()
for key, value in dict2.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = deep_merge(result[key], value)
else:
result[key] = value
return result
dict1 = {'a': 1, 'b': {'x': 10, 'y': 20}}
dict2 = {'b': {'y': 25, 'z': 30}, 'c': 3}
merged = deep_merge(dict1, dict2)
print(merged) # Output: {'a': 1, 'b': {'x': 10, 'y': 25, 'z': 30}, 'c': 3}
Error Handling for Invalid Dictionary Types
Be cautious when trying to merge non-dictionary objects:
# This will raise TypeError if x or y are not dictionaries
try:
z = {**x, **y}
except TypeError as e:
print(f"Error merging dictionaries: {e}")
# Alternative approach: convert to dict first
z = dict(**x, **y) if isinstance(x, dict) and isinstance(y, dict) else {}
Conclusion
Merging two dictionaries in a single expression in Python is straightforward using modern syntax. The dictionary unpacking method ({**dict1, **dict2}) is the recommended approach for Python 3.5+, providing a clean, readable one-line solution that creates a new dictionary without modifying the originals. For Python 3.9+, the union operator (dict1 | dict2) offers an even more concise alternative.
Key takeaways:
- Use
{**x, **y}for Python 3.5+ for the most readable syntax - Use
x | yfor Python 3.9+ for the cleanest operator syntax - For backward compatibility, create a custom merge function
- All methods handle duplicate keys by taking values from the second dictionary
- Be aware that shallow copying means nested mutable objects are shared
If you need to merge more complex structures or handle edge cases, consider extending the basic merging techniques with additional logic for nested dictionaries or type checking. The Python ecosystem continues to evolve, so stay updated on new dictionary operations as future versions are released.
Sources
- Stack Overflow - How do I merge two dictionaries in a single expression in Python?
- PythonHow - How to merge two dictionaries in a single expression in Python
- GeeksforGeeks - Merge two dictionaries in a single expression in Python
- SparkByExamples - Python Merge Two Dictionaries into Single
- Medium - Dictionary Unpacking ** in Python
- Finxter - How To Merge Two Python Dictionaries In A Single Expression In Python
- Vultr Docs - Python Program to Merge Two Dictionaries
- CodeRivers - Merging Two Dictionaries in Python: A Comprehensive Guide