Content · Programming · Python

Python Dictionary Merging with | and |=

The | operator combines two dictionaries into a new dictionary. The |= operator updates the left-hand dictionary with values from the right-hand mapping; overlapping keys use the right-side value. See two practical.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

A report needs user overrides applied to default options.

What You Need to Understand


The | operator combines two dictionaries into a new dictionary. The |= operator updates the left-hand dictionary with values from the right-hand mapping; overlapping keys use the right-side value.

When to Use It


A report needs user overrides applied to default options.

Step-by-Step Python Example


defaults = {"theme": "light", "page_size": 20}
changes = {"theme": "dark"}
combined = defaults | changes
print(combined)
print(defaults)
defaults |= changes
print(defaults)

How the Example Works


The first operation leaves the defaults untouched; the second changes the existing defaults mapping.

Example Output


{'theme': 'dark', 'page_size': 20}
{'theme': 'light', 'page_size': 20}
{'theme': 'dark', 'page_size': 20}
{'x': 2, 'y': 3}

A Second Example


Compare this smaller variation with the main example, then experiment with your own values.

print({"x": 1} | {"x": 2, "y": 3})

Important Behavior and Edge Cases


For ordinary dict objects the | operator expects dictionary operands, while |= accepts a suitable mapping or iterable of pairs. Do not assume both forms accept exactly the same inputs.

Try It Yourself


Merge two dictionaries that share one key and predict which value wins.

Common Beginner Mistakes


  • For ordinary dict objects the | operator expects dictionary operands, while |= accepts a suitable mapping or iterable of pairs. Do not assume both forms accept exactly the same inputs.
  • Treating missing dictionary keys, replacement precedence, and shallow copies as if they had identical behavior in every context.

Key Takeaways


  • The | operator combines two dictionaries into a new dictionary.
  • The first operation leaves the defaults untouched; the second changes the existing defaults mapping.
  • For ordinary dict objects the | operator expects dictionary operands, while |= accepts a suitable mapping or iterable of pairs.
Share this resourceSend this page to someone who may find it useful.