How do you merge two dictionaries in Python?
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
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+.