Show the ways to merge two Python dictionaries and what happens when both have the same key.
There are three ways to merge two dictionaries, and in all three of them the value from the dictionary on the right wins when both sides have the same key.
a = {'name': 'Ada', 'role': 'engineer'}
b = {'role': 'manager', 'team': 'platform'}
# 1. The union operator (Python 3.9 and later)
merged = a | b
print(merged) # {'name': 'Ada', 'role': 'manager', 'team': 'platform'}
print(a) # unchanged, because a new dictionary was made
# 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 key role is in both dictionaries, and the value manager replaces the value engineer. The first two forms leave the original dictionaries alone and produce a new dictionary, while update changes the first dictionary where it sits.
All three of them keep the insertion order of the left dictionary first, and then they add the keys from the right dictionary that were not already there. A key that exists on both sides keeps the position that 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 instead. And it needs both sides to be dictionaries, because you cannot union a dictionary with a list. If you want to merge a dictionary with a list of pairs, then dict(list_of_pairs) is the right tool.
One more point is worth raising in an interview. Merging with update quietly overwrites the old value. If you need to know whether a key was overwritten, for example to catch a clash in a configuration file, then check before you merge. The overlapping keys are found with a.keys() & b.keys().