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
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
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}
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.