
Daniel Roy Greenfeld
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)
“`

Search