Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Data types & structuresMiddleOccasionalPractical

What are the modern ways to merge two dictionaries in Python, and how do they handle overlapping keys?

Answer

Python 3.9 added the `|` merge operator and the `|=` in-place merge operator for dicts, giving a concise `merged = defaults | overrides` that returns a new dict. Older idioms include `{**defaults, **overrides}` unpacking and `defaults.copy(); result.update(overrides)`. In every case, when both dictionaries define the same key, the value from the right-hand or later-applied dictionary wins.

Strong answer includes

  • | and |= merge operators since 3.9
  • double-star unpacking as the older equivalent
  • right-hand or later dict's value wins on key collision

Practical example

Python example
config = defaults | user_overrides

produces a new dict where any key present in both takes the value from `user_overrides` .

#dict#syntax

Sources

The Python Standard LibraryPython Software Foundation · Authoritative behavior for built-in types and standard library modulesWhat's new in Python 3.14Python Software Foundation · Current-version language and runtime changes, including template strings and free-threading support