SyntaxStudy
Sign Up
Python Merging Dicts & Walrus Operator
Python Intermediate 10 min read

Merging Dicts & Walrus Operator

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 conflicts

In-place |=

defaults |= overrides   # updates defaults in-place

Older 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]
Example
base = {"debug": False, "timeout": 30, "retries": 3}
env  = {"timeout": 60, "api_key": "secret123"}

config = base | env
print(config)
# timeout is 60 (env wins)

import re
log = "ERROR 2024-05-01: Disk full"
if m := re.search(r"ERROR (.+?):", log):
    print("Error on:", m.group(1))
Pro Tip

The | operator for dicts returns a NEW dict; |= modifies the left dict in-place. The same distinction applies to sets.