AppDividend
Latest Code Tutorials

Python Update Operator(|=) with Example

0

The dictionary.update() method is used to merge the second dictionary into the first dictionary without creating any new dictionary and updating the value of the first dictionary, and return the first dictionary.

In Python 3.9+, two new operators have been introduced in dict class.

  1. merge (|) operator
  2. update (|=) operator.

We saw how the merge operator works in Python. In this tutorial, we will see how to use the update operator to update the dictionary.

Python update operator (|=)

With Python 3.9, a new operator is introduced called update operator ( |= ) in the dict class. The update operator (|=) performs an in-place+ operation between pairs of objects. The Update (|=) operation returns the left operand merged with the right operand.

Syntax

updated_dict = dictA |= dictB

Return Value

It merges dictA with dictB and returns the updated dictA.

Example

Let’s define two dictionaries and merge them into the first dictionary, and returns it.

dictA = {'astral': 45, 'prince': 70, 'deepak': 25}
dictB = {'dixon': 17, 'reliance': 23}

dictA |= dictB

print(dictA)

Output

{'astral': 45, 'prince': 70, 'deepak': 25, 'dixon': 17, 'reliance': 23}

This is an in-place merge-right (update) operation; equivalent to dictA.update(dictB).

You can see that the first dictionary dictA have been updated.

That is it for the new update operator in Python.

Leave A Reply

Your email address will not be published.

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