Interview Q&A / Python

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How do you merge two dictionaries in Python?

SHORT ANSWER

Use d1 | d2 in Python 3.9+, or {**d1, **d2} in older versions, or d1.update(d2) to modify d1 in place. When both have the same key, the value from the right-hand dictionary wins.

Explain it simply

Two class monitors each keep a list of roll number to marks. Merging means combining both lists into one. If a roll number appears in both, you must decide which wins. Python's rule: the later one overwrites the earlier one.

Example

python
d1 = {"a": 1, "b": 2}
d2 = {"b": 20, "c": 30}

print(d1 | d2)             # Output: {'a': 1, 'b': 20, 'c': 30}
print({**d1, **d2})        # Output: {'a': 1, 'b': 20, 'c': 30}

d1.update(d2)
print(d1)                  # Output: {'a': 1, 'b': 20, 'c': 30}

d3 = {"x": 1}
d3 |= {"y": 2}
print(d3)                  # Output: {'x': 1, 'y': 2}

| and {**a, **b} create a new dictionary, while update and |= change the existing one. The merge is shallow: nested values are shared, not copied.

What to say in the interview

"On 3.9 and later I use the | operator, or |= to update in place. For older versions, {a, b} or update(). On duplicate keys the right-hand value wins. All of these are shallow, so nested objects are still shared between the original and the result."

Common mistakes

  • Using d1 + d2. Dictionaries do not support +.

#python#dictionaries

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.