How to Merge Two Dictionaries in Python with the Spread Operator
Merge two Python dictionaries into one new dict using the ** unpacking (spread) operator, with later keys overriding earlier ones.
Python code
16 linesdef merge_two_dicts(dict1: dict, dict2: dict) -> dict:
"""Merge two dictionaries using the spread operator pattern."""
# The ** operator unpacks key-value pairs, later keys overwrite earlier ones
merged = {**dict1, **dict2}
return merged
if __name__ == "__main__":
# Example usage with overlapping and unique keys
dict_a = {"name": "Alice", "age": 30, "city": "NYC"}
dict_b = {"age": 31, "country": "USA", "job": "Engineer"}
result = merge_two_dicts(dict_a, dict_b)
print(result)
print(f"Type: {type(result).__name__}, Length: {len(result)}")
print(f"Overlapping key 'age' resolved to: {result['age']}")
Output
{'name': 'Alice', 'age': 31, 'city': 'NYC', 'country': 'USA', 'job': 'Engineer'}
Type: dict, Length: 5
Overlapping key 'age' resolved to: 31
How it works
The ** operator in {**dict1, **dict2} unpacks each dictionary's key-value pairs directly into a new dictionary literal. When both dictionaries contain the same key—here age—the value from the later dictionary (dict2) wins because it is unpacked last. This pattern creates a new dict, leaving the originals untouched, which is useful for immutability. It works in Python 3.5+ and is the most concise way to merge dictionaries without side effects.
Common mistakes
- Using a single `*` instead of `**`, which works for lists/tuples but not dicts
- Assuming the first dict's values win—later dicts override earlier ones
- Forgetting that nested dicts are not deep-merged, only top-level keys
Variations
- Use `dict2.update(dict1)` to merge in place when you can modify one dict
- Use `merged = dict1 | dict2` (Python 3.9+) for an operator-based merge
Real-world use cases
- Combining default configuration dicts with user-specified overrides when initializing an app.
- Merging API response payloads from multiple sources before storing them in a database.
- Building a unified request context by merging headers, user profile, and request params in a web framework.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.