Merge two dictionaries in a single expression in Python

Merging dictionaries is a common task in Python programming, and doing it efficiently and concisely can significantly enhance the readability and performance of your code. With the introduction of newer versions of Python, particularly Python 3.9, the process of merging dictionaries has become more intuitive and elegant. In this article, we’ll explore several methods to merge two dictionaries in a single expression.

Traditional Methods Before Python 3.9

Before diving into the newer, more straightforward approaches, it’s useful to understand how dictionary merging was typically done in earlier versions of Python.

1. Using the update() Method

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

merged_dict = dict1.copy()
merged_dict.update(dict2)

Output:

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

2. Using dictionary unpacking

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

merged_dict = {**dict1, **dict2}

Output:

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

Both approaches will result in merged_dict containing the merged key-value pairs from dict1 and dict2. Keep in mind that if there are common keys between the two dictionaries, the values from the second dictionary will overwrite the values from the first dictionary.

Merging Dictionaries in Python 3.9 and Later

Python 3.9 introduced a new, more readable way to merge dictionaries using the | operator.

Using the |= Operator

In addition to the | operator, Python 3.9 also introduced the |= operator for in-place dictionary merging.

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

merged_dict = dict1 | dict2
print(merged_dict)  

Output

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

This method updates dict1 with the contents of dict2, similar to how the update() method works, but with a more succinct syntax.