Show the ways to merge two Python dictionaries and what happens when both have the same key.
There are three ways to merge, and on a key conflict the value from the right-hand dictionary wins in all of them.
a = {"name": "Ada", "role": "engineer"}
b = {"role": "manager", "team": "platform"}
# 1. The union operator (Python 3.9+)
merged = a | b
print(merged) # {'name': 'Ada', 'role': 'manager', 'team': 'platform'}
print(a) # unchanged - a new dict was created
# 2. Dictionary unpacking
merged2 = {**a, **b}
print(merged2 == merged) # True
# 3. In-place update
a.update(b)
print(a) # {'name': 'Ada', 'role': 'manager', 'team': 'platform'}The role key exists in both, and manager replaces engineer. The first two forms leave the original dictionaries untouched and produce a new dictionary; update modifies the first dictionary in place.
All three preserve the insertion order of the left dictionary first, and then add any keys from the right that were not already present. A key that exists in both keeps the position it had in the left dictionary.
Two things to know about the union operator. It was added in Python 3.9, so older code uses the unpacking form or update. And it requires both sides to be dictionaries — you cannot union a dict with a list, whereas {**a, **b} also fails on a non-mapping. If you want to merge a dict with a list of pairs, dict(list_of_pairs) is the right tool.
One more point worth raising in an interview: merging with update silently overwrites. If you need to know whether a key was overwritten — to detect a configuration conflict, for instance — check before merging: overlapping = a.keys() & b.keys().