Dictionary Updates and Deletion
Core idea
A dictionary is mutable. d[key] = value adds a new pair or replaces the value for an existing key. d.update(other) applies entries from another mapping in place and returns None. del d[key] removes a required entry; d.pop(key, default) removes and returns a value or returns the supplied fallback if absent.
stock = {"tea": 3}stock["tea"] = 6stock["rice"] = 2print(stock)The existing count changes and rice is added.
Apply several changes
settings = {"speed": 1, "mode": "eco"}result = settings.update({"speed": 2, "limit": 8})print(settings)print(result)update changes settings itself; it does not return the dictionary.
Remove with a fallback
stock = {"tea": 2, "milk": 4}del stock["tea"]print(stock.pop("milk", 0))print(stock.pop("rice", 0))print(stock)del and pop remove present entries; missing rice returns zero.
Common mistake
Assigning d = d.update(other) loses the original binding because the method returns None. Without a fallback, pop on a missing key raises KeyError, as does del.
Practice
Create a small stock mapping, update two counts, remove a known item and safely remove an absent item.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Update and deletion
Check your understanding of updates and deletion.
What is printed?
d = {"x": 1}d["x"] = 3d["y"] = 4print(d)What is printed?
d = {"x": 1}print(d.update({"x": 4}))What is printed?
print({}.pop("x", 9))Which removes a known key without returning a value?