Merge Operator( | ) in Python Dictionary Class

From Python 3.9 onwards, a new feature was introduced for dictionaries: the merge operator (|).

This operator provides an easy and intuitive way to merge two dictionaries.

It returns a new dictionary containing the merged key-value pairs from both dictionaries. In cases of overlapping keys, the key-value pairs from the right-hand operand (the dictionary appearing after the | operator) take precedence.

It is more concise and more reader than the dictionary.update() method.

Syntax

dict1 | dict2

Example 1: Basic Usage

Visual Representation

Python merge operator( | )

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

merged_dict = dict1 | dict2

print(merged_dict)

Output

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

Example 2: Two dictionaries with overlapping keys

Visual Representation

Two dictionaries with overlapping keys

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

merged_dict = dict1 | dict2

print(merged_dict)

Output

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

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.