Merge Dictionaries in Python

You can merge dictionaries in Python using several methods depending on the version of Python you are using. Here are some common methods:

(1) Using update() method

The update() method merges the keys and values of one dictionary into another. If there are overlapping keys, the values from the second dictionary will overwrite values from the first.

For example:

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

dict1.update(dict2)
print(dict1)

Output:

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

This method modifies the dictionary in place.

(2) Using dictionary unpacking (Python 3.5+)

Using the ** unpacking operator, you can create a new dictionary containing the merged key-value pairs. If there are overlapping keys, the values from the rightmost dictionary take precedence.

For example:

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict3 = {'x': 20, 'y':30}

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

Output:

{'a': 1, 'b': 3, 'c': 4, 'x': 20, 'y': 30}

(3) Using the | operator (Python 3.9+)

Using the | merge operator, you can create a new dictionary with merged key-value pairs. If there are overlapping keys, the values from the rightmost dictionary take precedence.

For example:

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict3 = {'x': 20, 'y':30}

merged_dict = dict1 | dict2 | dict3
print(merged_dict)

Output:

{'a': 1, 'b': 3, 'c': 4, 'x': 20, 'y': 30}

You can use |= operator to update a list in place.

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

dict1 |= dict2
print(dict1)

Output:

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

(4) Using dictionary comprehension

You can merge dictionaries using dictionary comprehension.

For example:

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

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

Output:

{‘a’: 1, ‘b’: 3, ‘c’: 4}

(5) Using collections.ChainMap (Python 3.3+)

ChainMap combines multiple dictionaries into a single view without creating a new dictionary.

For example:

from collections import ChainMap

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

merged_dict = ChainMap(dict1, dict2)
print(dict(merged_dict))

Output:

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

In ChainMap, if there are duplicate keys, the value from the first dictionary is used.

Which method to use?

Use update() method to modify the first dictionary in place.

Use the unpacking operator (**) to create a new merged dictionary or merge multiple dictionaries (Python 3.5+).

Use the | merge operator to create a new merged dictionary or merge multiple dictionaries (Python 3.9+).

Use dictionary comprehension to create a new merged dictionary based on specific conditions or transformations of existing dictionaries.

Use ChainMap for a view without creating a new dictionary (Python 3.3+).