Merge two Dictionaries in Python

In Python, the merging of two dictionaries refers to combining two dictionaries’ key-value pairs into one dictionary. When common keys are present in both dictionaries, the values in the second dictionary will overwrite those in the first dictionary in the merged result. Python provides several ways to do this, depending on the version you’re using. Below is a detailed explanation of each method:

1. Using the update() Method

The update() method merges one dictionary into another by adding or updating key-value pairs. This modifies the original dictionary in-place.

# Original dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

# Merging using update()
dict1.update(dict2)

# Outputs
print("Merged dict1:", dict1)  # Output: {'a': 1, 'b': 3, 'c': 4}
print("dict2 remains unchanged:", dict2)  # Output: {'b': 3, 'c': 4}

Output:

Merged dict1: {'a': 1, 'b': 3, 'c': 4}
dict2 remains unchanged: {'b': 3, 'c': 4}

Explanation:

  1. The key-value pairs in dict2 are added to dict1.
  2. If there is a common key in the two dictionaries (say 'b'), then dict2 value will overwrite dict1.
  3. The update() method does not create a new dictionary; it modifies dict1.

2. Using the | Operator (Python 3.9+)

The | operator combines two dictionaries into a new dictionary, leaving the originals unchanged.

# Original dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

# Merging using | operator
merged_dict = dict1 | dict2

# Outputs
print("Merged dictionary:", merged_dict)  # Output: {'a': 1, 'b': 3, 'c': 4}
print("dict1 remains unchanged:", dict1)  # Output: {'a': 1, 'b': 2}
print("dict2 remains unchanged:", dict2)  # Output: {'b': 3, 'c': 4}

Output:

Merged dictionary: {'a': 1, 'b': 3, 'c': 4}
dict1 remains unchanged: {'a': 1, 'b': 2}
dict2 remains unchanged: {'b': 3, 'c': 4}

Explanation:

  1. The | operator creates a new dictionary called merged_dict.
  2. It overwrites values from the left dictionary, dict1, with values from the right dictionary, dict2, when duplicate keys are found.

3. Using Dictionary Comprehension

This method uses the unpacking operator (**) to combine dictionaries into a new dictionary. The originals remain unchanged.

# Original dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

# Merging using dictionary comprehension
merged_dict = {**dict1, **dict2}

# Outputs
print("Merged dictionary:", merged_dict)  # Output: {'a': 1, 'b': 3, 'c': 4}
print("dict1 remains unchanged:", dict1)  # Output: {'a': 1, 'b': 2}
print("dict2 remains unchanged:", dict2)  # Output: {'b': 3, 'c': 4}

Output:

Merged dictionary: {'a': 1, 'b': 3, 'c': 4}
dict1 remains unchanged: {'a': 1, 'b': 2}
dict2 remains unchanged: {'b': 3, 'c': 4}

Explanation:

  1. The ** operator unpacks the key-value pairs from each dictionary.
  2. Duplicate keys are treated just like the | operator: values from the second dictionary overwrite those of the first.

4. Using collections.ChainMap

ChainMap combines multiple dictionaries into a single view without creating a new dictionary. It prioritizes values from the first dictionary added.

from collections import ChainMap

# Original dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

# Merging using ChainMap
merged = ChainMap(dict2, dict1)

# Outputs
print("ChainMap merged view:", dict(merged))  # Output: {'b': 3, 'c': 4, 'a': 1}
print("Original dictionaries remain unchanged:")
print("dict1:", dict1)  # Output: {'a': 1, 'b': 2}
print("dict2:", dict2)  # Output: {'b': 3, 'c': 4}

Output:

ChainMap merged view: {'b': 3, 'c': 4, 'a': 1}
Original dictionaries remain unchanged:
dict1: {'a': 1, 'b': 2}
dict2: {'b': 3, 'c': 4}

Explanation:

  1. ChainMap(dict2, dict1) combines dict2 and dict1 into a single view.
  2. If a key exists in both dictionaries, the value from the first dictionary (dict2) takes precedence.

5. Using a For Loop

Manually merge dictionaries by iterating through one dictionary and adding its items to another.

# Original dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

# Merging using a for loop
merged_dict = dict1.copy()  # Start with a copy of dict1
for key, value in dict2.items():
    merged_dict[key] = value

# Outputs
print("Merged dictionary:", merged_dict)  # Output: {'a': 1, 'b': 3, 'c': 4}
print("dict1 remains unchanged:", dict1)  # Output: {'a': 1, 'b': 2}
print("dict2 remains unchanged:", dict2)  # Output: {'b': 3, 'c': 4}

Output:

Merged dictionary: {'a': 1, 'b': 3, 'c': 4}
dict1 remains unchanged: {'a': 1, 'b': 2}
dict2 remains unchanged: {'b': 3, 'c': 4}

Explanation:

  1. A copy of dict1 makes sure the original dictionary is not altered.
  2. A for loop runs over the elements in dict2 and appends them to merged_dict.
  3. If keys overlap, values from dict2 overwrite those in dict1.

Full Comparison Table

MethodCreates New Dictionary?Modifies Original?Handles Duplicate Keys?Python Version
update()NoYes (dict1)Overwrites with dict2All versions
`` OperatorYesNoOverwrites with dict2
Dictionary ComprehensionYesNoOverwrites with dict2All versions
ChainMapNo (creates view)NoPrioritizes first dictAll versions
For LoopYesNoOverwrites with dict2All versions