dict.update()
Python · Dictionaries
Theory
.update(other) merges key-value pairs into a dictionary, in place. For each pair in other: if the key already exists its value is overwritten, and if it is new it is added at the end. employee.update({'salary': 70000, 'bonus': 5000}) changes salary to 70000 and adds bonus, giving {'name': 'Asha', 'salary': 70000, 'bonus': 5000}. It returns None, so do not write employee = employee.update(...).
update() accepts another dict, an iterable of (key, value) pairs, or keyword arguments: employee.update(city='Pune'). When several sources contain the same key, the last one wins. If you want a new merged dict and must keep the original unchanged, use the merge operator new = a | b (Python 3.9+) or {**a, **b}; a |= b is the in-place version, like update(). update() is a shallow merge: nested dicts are replaced as a whole, not merged recursively.
Why we use it
Applying changes to a record, overlaying user settings on defaults, or combining data from two sources are everyday tasks. update() does all of it in one call instead of assigning keys one by one.
When to use it
Use update() to change or add several keys in an existing dict. Use a | b or {**a, **b} when you need a new dict and must keep the originals. For nested configs that need deep merging, write a small recursive function.
How it works
- Call employee.update({'salary': 70000, 'bonus': 5000})
- Take the next pair from the argument
- Is the key already in employee? Yes: Overwrite its value in place. No: Add the new pair at the end.
- Repeat for every pair
- Return None; employee now holds the merged data
Syntax
dict.update(other_dict)Example
employee = {'name': 'Asha', 'salary': 65000}
employee.update({'salary': 70000, 'bonus': 5000})
print(employee)Key points
- Existing keys get overwritten; new keys get added
- Modifies the dictionary in place and returns None
- Also accepts pairs or keywords: d.update(city='Pune')
- a | b creates a new merged dict and leaves both unchanged
- Shallow merge: nested dicts are replaced, not combined