Python  

How to Merge Two Dictionaries in Python

Introduction

Merging two dictionaries in Python is a common task for developers, especially when working with data structures, APIs, or configuration files. Python dictionaries store data in key-value pairs, and there are multiple ways to combine them depending on your version of Python and desired output.

🧠 What Is a Dictionary in Python?

A dictionary is a built-in Python data structure that stores key-value pairs. Each key in a dictionary must be unique, and it maps to a specific value.

Example

student = {
    "name": "Alice",
    "age": 21,
    "course": "Computer Science"
}
print(student["name"])  # Output: Alice

Why Merge Dictionaries?

Merging dictionaries enables you to combine data from multiple sources into a single, unified structure. This is especially useful when:

  • Combining configuration settings from different files.

  • Merging API responses.

  • Updating one dictionary with values from another.

When merging, if both dictionaries contain the same key, the value from the second dictionary typically overwrites the value from the first one.

Method 1. Using the update() Method

The update() method is the traditional way to merge two dictionaries. It adds key-value pairs from one dictionary into another.

Example

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

dict1.update(dict2)
print(dict1)

Output

{'a': 1, 'b': 3, 'c': 4}

Explanation

  • The key 'b' exists in both dictionaries, so its value is updated to 3 (from dict2).

  • The update() method modifies dict1 directly — it doesn’t return a new dictionary.

Best for: When you want to merge dictionaries in-place.

Method 2. Using Dictionary Unpacking (** Operator)

Starting with Python 3.5, you can merge two dictionaries easily using the ** unpacking operator.

Example

dict1 = {"x": 10, "y": 20}
dict2 = {"y": 30, "z": 40}

merged_dict = {**dict1, **dict2}
print(merged_dict)

Output

{'x': 10, 'y': 30, 'z': 40}

Explanation

  • The ** operator unpacks both dictionaries into a new one.

  • If duplicate keys exist, the last one (dict2) takes priority.

Best for: Creating a new merged dictionary without modifying the originals.

Method 3. Using the | (Pipe) Operator — Python 3.9+

From Python 3.9 onward, the | operator provides a clean and readable way to merge dictionaries.

Example

dict1 = {"name": "John", "age": 25}
dict2 = {"age": 30, "city": "New York"}

merged_dict = dict1 | dict2
print(merged_dict)

Output

{'name': 'John', 'age': 30, 'city': 'New York'}

Explanation

  • The | operator creates a new merged dictionary.

  • The |= operator can be used to update an existing dictionary:

dict1 |= dict2
print(dict1)

Best for: Modern Python (3.9+) — clean and concise syntax.

Method 4. Using Dictionary Comprehension

If you want to customize how keys and values are merged, dictionary comprehension gives you flexibility.

Example

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

merged = {k: v for d in [dict1, dict2] for k, v in d.items()}
print(merged)

Output

{'a': 1, 'b': 3, 'c': 4}

Explanation

  • Iterates through both dictionaries.

  • Adds all key-value pairs into one.

  • The last occurrence of each key is retained.

Best for: When you need custom merge logic or filtering.

Bonus: Merging with Conflict Handling

Sometimes you may want to handle key conflicts differently — for example, by adding their values instead of replacing them.

Example

dict1 = {"a": 10, "b": 20}
dict2 = {"b": 30, "c": 40}

merged = {key: dict1.get(key, 0) + dict2.get(key, 0) for key in set(dict1) | set(dict2)}
print(merged)

Output

{'a': 10, 'b': 50, 'c': 40}

Best for: When you want to combine numeric values instead of overwriting.

Performance Comparison

MethodPython VersionReturns New Dict?Modifies Original?PerformanceBest Use Case
update()All versionsNoesFastSimple updates
** Operator3.5+YesNoFastModern Python merging
`` Operator3.9+YesNoVery fast
Dict ComprehensionAll versionsYesNoModerateCustom merge logic
Conflict HandlingAll versionsYesNoModerateAdditive merges

Summary

Merging dictionaries in Python is simple and flexible. You can choose between traditional methods like update(), modern approaches like the | or ** operators, or even custom dictionary comprehensions for advanced scenarios.

  • Use update() if you want to modify a dictionary in place.

  • Use {**dict1, **dict2} for Python 3.5+ when you need a new dictionary.

  • Use the | operator in Python 3.9+ for the cleanest syntax.

  • Use dictionary comprehension for full control and customization.

By mastering these methods, you’ll write more efficient, clean, and Pythonic code — a valuable skill for both beginners and professionals working with modern Python applications.