Sub topic 4
Adding, Updating and Removing Entries
This chapter assumes you can create a dictionary, read it with [] and get(), and know that dictionaries are mutable. Here you will change a dictionary in place. You will add entries, replace values, and remove entries without surprise errors.
Assignment adds and updates
One syntax does two jobs. If the key is absent, assignment adds an entry. If the key exists, assignment replaces its value.
stock = {"apple": 3}
stock["pear"] = 5 # key is new, so it is added
stock["apple"] += 2 # key exists, so its value is replaced
print(stock) # {'apple': 5, 'pear': 5}Python never warns you that an assignment replaced something. A typo in a key name silently creates a second entry.
Augmented assignment such as += first reads the key and then writes it. If the key is missing, the read step raises KeyError.
counts = {}
try:
counts["x"] += 1
except KeyError:
print("KeyError: 'x' was never set")
counts["x"] = counts.get("x", 0) + 1
print(counts) # {'x': 1}Changing many entries with update()
update() copies entries from another mapping, from key-value pairs, or from keyword arguments. Existing keys get new values and new keys are appended.
profile = {"name": "Ada"}
profile.update({"role": "admin"}, name="Ada L.")
print(profile) # {'name': 'Ada L.', 'role': 'admin'}update() changes the dictionary in place and returns None. Writing profile = profile.update(...) replaces your dictionary with None.
Removing entries
Python gives you several ways to remove entries. They differ in what they return and in what happens when the key is missing.
| Tool | Returns | Missing key |
|---|---|---|
| `del d[k]` | nothing | raises `KeyError` |
| `d.pop(k)` | the removed value | raises `KeyError` |
| `d.pop(k, default)` | the removed value, or `default` | no error |
| `d.popitem()` | the last inserted `(key, value)` pair | raises `KeyError` if the dictionary is empty |
| `d.clear()` | nothing | removes every entry |
stock = {"apple": 5, "pear": 5}
removed = stock.pop("pear") # remove and return the value
stock.pop("kiwi", None) # no error when the key is absent
del stock["apple"] # remove a key
print(removed, stock) # 5 {}
queue = {"a": 1, "b": 2}
print(queue.popitem()) # ('b', 2)
print(queue) # {'a': 1}popitem() removes entries in last-in, first-out order. This is guaranteed from Python 3.7 onward, because dictionaries keep insertion order.
Common errors
- Assuming
d[k] = vfails whenkexists. It overwrites the old value without any message. - Using
+=or.append()on a key that was never created. Create the entry first, or useget()with a default. - Storing the result of
update(),clear()orpop()in the dictionary's own name.update()andclear()returnNone, andpop()returns the removed value instead of the dictionary. - Removing keys inside a
forloop over the same dictionary. That raises aRuntimeError. A later chapter covers the safe pattern.
Exercise
Given inventory = {"nails": 100, "screws": 40}, write code that adds 25 to "screws", adds a new key "bolts" with value 10, and removes "nails" without raising an error even if "nails" were already missing. What does the dictionary contain at the end?
Show answer
Use inventory["screws"] += 25, then inventory["bolts"] = 10, then inventory.pop("nails", None). The final dictionary is {'screws': 65, 'bolts': 10}.
Exercise
A teammate writes config = config.update({"debug": True}). What is config afterwards, and why?
Show answer
config is None. update() modifies the dictionary in place and returns None, so the assignment overwrites the dictionary with that return value. The fix is to call config.update({"debug": True}) on its own line.