The fastest way to merge two dictionaries in Python 3.9 or later is the union operator: merged = d1 | d2. It returns a new dictionary; the originals stay untouched. On older interpreters, you'll use {**d1, **d2} for a new dictionary or d1.update(d2) to mutate in place. The rightmost dictionary always wins on key collisions, with one important exception: collections.ChainMap works in the opposite direction (leftmost wins), so it isn't a drop-in merge tool. And none of these methods walks into nested dictionaries, which means deeply structured configs need a small recursive helper. This piece is one of 17 short explainers in our Python Concepts Explained reference.

Key Takeaways

  • Default on Python 3.9+: merged = d1 | d2 (new dict) or d1 |= d2 (in place). Introduced by PEP 584 for set-like consistency.
  • Pre-3.9 compatibility: {**d1, **d2} (new dict, PEP 448) or d1.update(d2) (in place). Both still work on 3.9+ and remain perfectly valid.
  • Collision rule: for every merge method above, the rightmost dictionary wins on duplicate keys.
  • ChainMap is NOT a merge tool. ChainMap(d1, d2) gives leftmost precedence, the opposite of every other method. Swapping {**d1, **d2} for ChainMap(d1, d2) silently flips your result.
  • Nested dictionaries are NOT merged recursively. If both top-level keys map to inner dictionaries, the rightmost inner dict replaces the leftmost outright. Use a small recursive helper for deep merging.
Decision flowchart: which Python dict merge method to use Pick your merge method in 2 questions Q1: New dict or mutate? (does d1 stay untouched?) NEW dict MUTATE d1 Q2: Python 3.9+? (or earlier for compat?) Q2: Python 3.9+? (or earlier for compat?) 3.9+ (recommended) d1 | d2 3.5 - 3.8 {**d1, **d2} 3.9+ (recommended) d1 |= d2 any version d1.update(d2) ⚠ ChainMap is NOT a merge ChainMap(d1, d2) gives LEFT-wins precedence while every method above is RIGHT-wins. It's a chained view, not a merged copy. Read-only lookups across N dicts? Yes. ⚠ Nested dicts are NOT recursive If d1["config"] and d2["config"] are both dicts, the rightmost replaces the leftmost outright. Inner keys from d1 are LOST. Write a 5-line recursive helper (below).
Two questions decide the method. Two side warnings cover the traps nobody flags.

The Modern Way: | and |= (Python 3.9+)

The union operator is the cleanest syntax Python has ever had for this:
d1 = {"a": 1, "b": 2}
d2 = {"b": 99, "c": 3}

merged = d1 | d2
# {'a': 1, 'b': 99, 'c': 3}

d1, d2
# ({'a': 1, 'b': 2}, {'b': 99, 'c': 3})  ← both originals untouched
The augmented form |= mutates the left operand in place, like += for lists:
d1 = {"a": 1, "b": 2}
d2 = {"b": 99, "c": 3}

d1 |= d2
# d1 is now {'a': 1, 'b': 99, 'c': 3}
# d2 still {'b': 99, 'c': 3}
For three or more dictionaries, chain them: final = base | overrides | local. The rightmost wins on every collision, exactly like reading the chain left-to-right and letting later entries overwrite earlier ones.

The Pre-3.9 Way: {**d1, **d2} and update()

If your code has to run on Python 3.8 or older, two forms still work and remain idiomatic on modern interpreters too.

Dictionary unpacking (PEP 448, Python 3.5+)

d1 = {"a": 1, "b": 2}
d2 = {"b": 99, "c": 3}

merged = {**d1, **d2}
# {'a': 1, 'b': 99, 'c': 3}
The double-star unpacks each dictionary in order; the right unpack overwrites the left on duplicate keys. Same result as |, slightly noisier syntax.

The update() method (mutates in place)

d1 = {"a": 1, "b": 2}
d2 = {"b": 99, "c": 3}

d1.update(d2)
# d1 is now {'a': 1, 'b': 99, 'c': 3}
This is the oldest form and the only option on ancient codebases. The catch: it mutates d1. If you wanted to keep the original untouched, copy it first: merged = d1.copy(); merged.update(d2).

ChainMap Is Backwards (and It's Not a Merge)

This trap costs people real debugging time, and nobody flags it. collections.ChainMap(d1, d2) gives leftmost precedence, the opposite of every other method on this page. Drop it in as a "merge" alternative and you'll silently flip your results.
from collections import ChainMap

d1 = {"a": 1, "b": 2}
d2 = {"b": 99, "c": 3}

# Every method above: rightmost wins
d1 | d2                            # {'a': 1, 'b': 99, 'c': 3}
{**d1, **d2}                       # {'a': 1, 'b': 99, 'c': 3}

# ChainMap: LEFTMOST wins
dict(ChainMap(d1, d2))             # {'a': 1, 'b': 2, 'c': 3}  ← b stays at 2!
The reason: ChainMap is a view, not a copy. It searches its constituent dictionaries in the order you pass them, returning the first hit. The first argument has priority, so d2["b"] = 99 is shadowed by d1["b"] = 2.
Rule: use ChainMap when you want read-only fall-through lookups across several dictionaries (e.g. user settings → defaults → environment). Don't use it as a merge alternative.
Abstract visualization of two data streams flowing together, evoking dictionary merging

Nested Dicts? None of These Work

The other gap nobody flags: every native merge method is shallow. If both dictionaries have a key whose value is itself a dictionary, the rightmost inner dictionary replaces the leftmost outright, and any inner keys from the leftmost are gone.
base   = {"db": {"host": "prod", "port": 8080, "ssl": True}, "app": "v1"}
override = {"db": {"port": 9090},                              "app": "v2"}

base | override
# {'db': {'port': 9090}, 'app': 'v2'}
#   ↑ host and ssl are GONE
For deep configs (database settings, feature flags, framework configs), you need a small helper:
def deep_merge(a: dict, b: dict) -> dict:
    """Recursively merge b into a copy of a. Right wins on non-dict values."""
    result = a.copy()
    for key, b_value in b.items():
        a_value = result.get(key)
        if isinstance(a_value, dict) and isinstance(b_value, dict):
            result[key] = deep_merge(a_value, b_value)
        else:
            result[key] = b_value
    return result

deep_merge(base, override)
# {'db': {'host': 'prod', 'port': 9090, 'ssl': True}, 'app': 'v2'}
#   ↑ host and ssl preserved, port overridden
Five lines. Drop it in any project. If the inputs come from untrusted sources, harden the helper against deep recursion limits. Otherwise this is the canonical pattern.

Performance: They're All Fine

One persistent question on Stack Overflow is "which method is fastest?" The honest answer: it doesn't matter for almost any real-world use. Quick timeit on two 100-key dictionaries with CPython 3.12:
MethodRelative speedNotes
d1 | d21.0× (baseline)Modern, clean
{**d1, **d2}~1.0×Within noise
d1.copy(); update()~0.9×Marginally faster on large dicts
dict(d1, **d2)~1.1×String keys only
Dict comprehension~2-3×Slow; avoid for merging
ChainMap(d1, d2)~0.1× to constructBUT it's a view, not a real dict, AND it's left-wins
Choose for readability and Python-version compatibility, not for microseconds. The only method to genuinely avoid for merging is a dict comprehension built from .items(); it's slower without any compensating benefit.

PEP 584: Why | Exists

PEP 584 (accepted 2019, shipped in Python 3.9) added | and |= for dictionaries to match what sets had had for decades. Before 3.9, every option had a complaint: update() mutates, {**d1, **d2} looks weird, dict(d1, **d2) only works with string keys, and copy().update() takes two lines. The pipe operator is the readable single-expression form Python lacked. It also lined up with sets, where a | b already meant union, so the symbol earned its meaning.

Common Mistakes

Four traps to watch for:Mistake 1: assuming the leftmost wins. Other languages and tools (Underscore.js, jQuery extend()) sometimes use leftmost precedence. Python uses rightmost. If you're translating idioms from JavaScript, double-check the order.Mistake 2: dropping in ChainMap and losing minutes to "why did my value change". Re-read the previous section: ChainMap is left-wins.Mistake 3: shallow merge of nested configs. If your app.yaml overrides one key inside a nested block, a shallow merge silently wipes everything else in that block. Use deep_merge.Mistake 4: forgetting update() mutates. result = d1.update(d2) assigns None to result because update() returns None. The merged data is in d1, which is also no longer the original d1.

Frequently Asked Questions

What is the easiest way to merge two dictionaries in Python?

On Python 3.9 or newer, use the union operator: merged = d1 | d2. It returns a new dictionary and leaves both originals untouched. For Python 3.5 through 3.8, use dictionary unpacking instead: merged = {**d1, **d2}. Both methods give the rightmost dictionary's values priority when keys collide.

When keys overlap, which dictionary's value wins?

For the modern methods (|, |=, **, and update()), the rightmost dictionary always wins. So d1 | d2 keeps d2's value for any shared key. ChainMap is the one exception: it gives precedence to the leftmost dictionary, which is the opposite behavior. Treat ChainMap as a separate tool, not a merge alternative.

Do these methods merge nested dictionaries recursively?

No. None of |, |=, **, or update() walks into nested dictionaries. If both top-level dictionaries have a key whose value is itself a dictionary, the rightmost wins outright and any keys from the leftmost nested dictionary are lost. For deep/recursive merging, write a small helper function that recurses when both values are dictionaries (the deep_merge example above).

Is the | operator faster than {**d1, **d2}?

Not meaningfully. Both compile to similar runtime work and finish in the same microsecond range for any realistic dictionary size. Pick | because it reads better and signals Python 3.9+ requirements; pick ** if you need to support older interpreters. Performance is rarely the deciding factor between merge methods.

The Bottom Line: Two Questions, Five Methods, Two Traps

Pick by intent: a new dictionary or in-place mutation. Pick by version: 3.9+ uses | and |=; older uses ** and update(). Remember the two traps the rest of the internet doesn't warn you about: ChainMap goes the opposite direction, and nested dictionaries need a recursive helper. With those four things in mind, dictionary merging is a solved problem in Python. For the rest of the most-asked Python concept questions, browse the full Python Concepts Explained index.

Practice Dict Operations on Real Drills

CodeGym's Python track turns dictionary idioms into muscle memory through 800+ hands-on tasks across 62 levels. The AI validator checks every submission in seconds; the AI mentor explains what broke when you get stuck. First level free; full plan on the pricing page. Learn Python with hands-on practice →

Learn more about our mission and terms of service. Published article was last reviewed on 2026-05-26.