Merging Dicts & the Walrus Operator
Python 3.9+ introduced the merge (|) and update (|=) operators for dicts. The walrus operator (:=) assigns and evaluates in one step.
Merging with | (Python 3.9+)
defaults = {"color": "blue", "size": "medium", "weight": 1.0}
overrides = {"color": "red", "weight": 2.5}
merged = defaults | overrides
print(merged)
# {'color': 'red', 'size': 'medium', 'weight': 2.5}
# overrides wins on conflictsIn-place |=
defaults |= overrides # updates defaults in-placeOlder Approaches
# Python 3.5+ unpacking
merged = {**defaults, **overrides}
# update() method
d = defaults.copy()
d.update(overrides)Walrus Operator (:=)
# Assign and test in one expression
import re
data = "Order #1042 placed on 2024-01-15"
if m := re.search(r"#(\d+)", data):
print(f"Order ID: {m.group(1)}") # 1042
# In a while loop
import random
while (n := random.randint(1, 10)) != 7:
print(f"Got {n}, trying again...")
print("Got 7!")Walrus in Comprehensions
results = [y for x in range(10) if (y := x**2) > 20]
print(results) # [25, 36, 49, 64, 81]