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.

Easy Python 3.5+ Aug 9, 2026 Dictionaries & sets 15 views 0 copies

Python code

16 lines
Python 3.5+
def 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

stdout
{'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

  1. Use `dict2.update(dict1)` to merge in place when you can modify one dict
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.