Friday, May 23, 2025
HomePythonPipe operator for merging dictionaries

Pipe operator for merging dictionaries



TIL: Pipe operator for merging dictionaries















Daniel Roy Greenfeld

Daniel Roy Greenfeld

About | Articles | Books | Jobs | Tags | Search

In Python 3.9 and later, the pipe operator | can be utilized to merge dictionaries.

Pipe `|` returns a brand new dictionary containing the key-value pairs from each operands.

“`python
a = {‘a’: 1, ‘b’: 2}
b = {‘c’: 3, ‘d’: 4}
# Just like a.replace(b), however returns a brand new dictionary as a substitute of constructing a change in-place
merged = a | b
print(a)
“`

If there are duplicate keys, the worth from the right-hand operand will overwrite the worth from the left-hand operand.

“`python
left = {‘a’: 1, ‘b’: 2}
proper = {‘a’: 3, ‘b’: 4}
merged = left | proper
print(merged)
“`

The `|=` is said, updating the left-hand operand in place very similar to the `+=` operator.

“`python
authentic = {‘a’: 1, ‘b’: 2}
new = {‘b’: 3, ‘c’: 4}
authentic |= new # Analogous to authentic.replace(new)
print(authentic)
“`

Tags: TIL python

← Again to all articles




RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments