Lackson Munthali

Android / iOS Developer

Web Designer

Freelancer

Blogger

0

No products in the cart.

Lackson Munthali

Android / iOS Developer

Web Designer

Freelancer

Blogger

Blog Post

How to Merge or Update Dictionary in Python using | and |= operators in Python

March 3, 2022 Python
How to Merge or Update Dictionary in Python using | and |= operators in Python

The below operators have been added to Python 3.9 built-in dict class. It has to be noted that the two operators complement the existing dict.update and {**d1, **d2} methods of merging dicts.

1. How to Merge Dictionary in Python – ( | ) or dict union

Example 1:

a = {"a": 1, "b": 2}
b = {"c": 3, "d": 4}
print(a | b)
# result {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Example 2:

a = {"a": 1, "b": 2}
b = {"a": 3, "d": 4}
print(a | b)
# results {'a': 3, 'b': 2, 'd': 4}

From the above examples am sure you have noticed that the dict union returns a new dict consisting of the left operand merged with the right operand. For this to work each operand must be a dict (or an instance of a dict subclass). If a key appears in both operands, the last-seen value (i.e. that from the right hand operand) wins like in the example 2 above with key a.

2. How to update Dictionary in Python – Update ( |= ) or Augmented assignment

The augmented assignment version operates in-place:

Example 1:

a = {"a": 1, "b": 2}
b = {"a": 3, "d": 4}
print(a |= b)
# results {'a': 3, 'b': 2, 'd': 4}

The |= operator behaves identically to the update method called with a single position argument, so it also accepts anything implementing the Mapping protocol (more specifically, anything with the keys and __getitems__ methods) or iterables of key-value pairs. This is more like to list += and list.extend, which accepts any iterable, not just lists. continued from the above:

a | [('year', 2021)]
print(a)
# results TypeError: unsupported operand type(s) for |: 'dict' and 'list'

a |= [('year', 2021)]
print(a)
# results {'a': 3, 'b': 2, 'd': 4, 'year': 2021}

When new keys are added, their order matches their order within the right-hand mapping, if any exists for its type.

But why change the way we merge and update dictionaries?

It was noted that the current ways to merge two dicts have several disadvantages.

dict.update d1.update(d2) modifies d1 in-place. e=d1.copye.update(d2) is not an expression and needs a temporary variable.

{**d1, *d2} Dict unpacking looks ugly and is not easily discoverable. Few people would be able to guess what it means the first time thy see it, or think of it as the “obvious way” to merge two dicts.

Even Guido the creator of Python once said:

“… if you were to ask a typical Python user how to combine two dicts into a new one, I doubt many people would think of {*d1, *d2}. I know I myself had forgotten …”

The truth is {*d1, *d2} ignores the types of the mapping and always returns a dict.type(d1) ({*d1, **d2}) fails for dict subclasses such as defaultdict that have an incompatible init method.

So What do you think about the operators?

Write a comment