logo
Python Data Structures - Interview Questions and Answers
How do you merge two dictionaries in Python?

You can merge two dictionaries in Python using several methods. Here are the most common ways:

1. Using the update() Method (Modifies Original Dictionary)
  • The update() method adds key-value pairs from one dictionary to another.
  • If a key exists in both dictionaries, the value from the second dictionary overwrites the value in the first.
Example :
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}

dict1.update(dict2)  # Modifies dict1
print(dict1)  # Output: {'a': 1, 'b': 3, 'c': 4}

* Best when you want to modify an existing dictionary.


2. Using Dictionary Unpacking (**) (Creates a New Dictionary)
  • This method merges dictionaries into a new one without modifying the originals.
  • If keys overlap, values from later dictionaries overwrite earlier ones.
Example :
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}

merged_dict = {**dict1, **dict2}
print(merged_dict)  # Output: {'a': 1, 'b': 3, 'c': 4}

* Best when you want to create a new merged dictionary.


3. Using the | Operator (Python 3.9+)
  • Introduced in Python 3.9, | merges two dictionaries and returns a new one.
  • Overlapping keys take the value from the second dictionary.
Example (Python 3.9+ Only) :
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}

merged_dict = dict1 | dict2
print(merged_dict)  # Output: {'a': 1, 'b': 3, 'c': 4}

* Best when using Python 3.9+ and you need a clean syntax.


4. Using a Dictionary Comprehension (Advanced)
  • This method gives more control, allowing transformations while merging.
Example :
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}

merged_dict = {key: dict2.get(key, dict1.get(key)) for key in dict1.keys() | dict2.keys()}
print(merged_dict)  # Output: {'a': 1, 'b': 3, 'c': 4}

* Best when you need custom merging logic.


Which Method to Use?
Method Modifies Original? Creates New Dict? Python Version
update() Yes No Any
** (Unpacking) No Yes 3.5+
` ` (Union Operator) No Yes
Dictionary Comprehension No Yes Any