What is the Merge Operator in Python(Introduced in Python3.9)

The merge operator is a new feature in Python 3.9 that allows you to “merge two dictionaries”. The syntax of the merge operator is a “pipe character (|)”.

Syntax

dict1 | dict2

Operands

  1. dict1: Current dictionary object
  2. dict2: Another dictionary object

Return value

It returns the merged dictionary as a dict instance. The “merge operator” creates a new dictionary containing both dictionaries’ keys and values. If there are duplicate keys, the value from the right-hand dictionary will be used.

Example: How to Use Merge Operator in Python

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

new_dict = dict1 | dict2

print(new_dict)

Output

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

The “merge operator” is a convenient way to merge two dictionaries. It is shorter, more concise than the “dictionary.update()” method, and more readable.

Leave a Comment

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