Sub topic 4
Adding, updating and removing entries
This chapter assumes you can create a dictionary and read from it with [], get() and in. You should also know the difference between mutable and immutable objects, because dictionaries are mutable and that has consequences. After this chapter you will be able to change a dictionary in place, choose the right removal method, and predict what happens when a key is missing.
Assignment adds or replaces
Assigning to a key does one of two things. If the key is absent, a new entry is created. If the key is present, its value is replaced. Python does not distinguish the two cases in the syntax.
stock = {"apple": 3}
stock["pear"] = 5 # new key: entry is added
stock["apple"] += 2 # existing key: value is replaced
print(stock) # {'apple': 5, 'pear': 5}Augmented assignment such as stock["apple"] += 2 first reads the value and then writes it back. It therefore raises KeyError if the key does not exist yet. Plain assignment never raises for a missing key.
stock = {}
try:
stock["kiwi"] += 1
except KeyError as exc:
print("KeyError:", exc) # KeyError: 'kiwi'This is why counting code needs either a guard, get() with a default, or one of the tools covered in the counting and grouping chapter.
stock = {}
stock["kiwi"] = stock.get("kiwi", 0) + 1
print(stock) # {'kiwi': 1}Position and replacement
Dictionaries remember insertion order. Replacing the value of an existing key keeps that key's original position. Deleting a key and adding it again moves it to the end.
d = {"a": 1, "b": 2, "c": 3}
d["a"] = 10 # replaced: stays first
del d["b"]
d["b"] = 20 # re-added: goes last
print(d) # {'a': 10, 'c': 3, 'b': 20}Changing many entries with update()
update() merges entries from another source into the dictionary, in place. It accepts a dictionary, an iterable of key-value pairs, or keyword arguments. Existing keys are overwritten and new keys are added.
prices = {"apple": 0.5, "pear": 0.75}
prices.update({"pear": 0.8, "fig": 1.2}) # from a dict
prices.update(kiwi=0.9) # from keyword arguments
prices.update([("plum", 0.6)]) # from pairs
print(prices)
# {'apple': 0.5, 'pear': 0.8, 'fig': 1.2, 'kiwi': 0.9, 'plum': 0.6}update() returns None. A common mistake is writing prices = prices.update(...), which replaces your dictionary with None.
Keyword arguments only work when the keys are valid identifiers, such as kiwi. For keys like "two words" or integers, pass a dictionary or a list of pairs.
The |= operator does the same job as update() for two dictionaries. The merging chapter compares them with | and ** unpacking.
Adding only if absent: setdefault()
setdefault(key, default) returns the value for key. If the key is missing, it first inserts key with default, then returns that value. It is a read and a conditional write in one call.
config = {"theme": "light"}
print(config.setdefault("theme", "dark")) # light (existing value wins)
print(config.setdefault("font", 12)) # 12 (inserted)
print(config) # {'theme': 'light', 'font': 12}It is most useful when the default is a mutable container you want to fill.
groups = {}
for word in ["apple", "avocado", "banana"]:
groups.setdefault(word[0], []).append(word)
print(groups) # {'a': ['apple', 'avocado'], 'b': ['banana']}One gotcha is that the default argument is built on every call, even when the key exists and the new object is thrown away. For a cheap [] that does not matter. For an expensive default, check with in first or use defaultdict.
Removing entries
Python gives you several ways to remove entries. They differ in what they return and how they behave when the key is missing.
| Tool | Removes | Returns | Missing key |
|---|---|---|---|
| `del d[k]` | one key | nothing | raises `KeyError` |
| `d.pop(k)` | one key | the value | raises `KeyError` |
| `d.pop(k, default)` | one key | the value or `default` | returns `default` |
| `d.popitem()` | the last-inserted entry | a `(key, value)` tuple | raises `KeyError` if the dictionary is empty |
| `d.clear()` | every entry | nothing | not applicable |
del and pop
Use del when the key must exist and you do not need the value. Use pop() when you want the value, or when the key may be absent.
cart = {"apple": 3, "pear": 5, "fig": 2}
print(cart.pop("pear")) # 5
print(cart.pop("kiwi", 0)) # 0 (no error: default supplied)
del cart["apple"]
try:
del cart["apple"] # already gone
except KeyError as exc:
print("KeyError:", exc) # KeyError: 'apple'
print(cart) # {'fig': 2}A KeyError from del is often useful because it signals a bug: you expected the key to exist and it did not. Reach for pop(k, None) only when absence is a normal case.
popitem
Since Python 3.7, popitem() removes and returns the most recently inserted entry (last in, first out). That makes a dictionary usable as a simple stack of pairs.
queue = {"a": 1, "b": 2, "c": 3}
print(queue.popitem()) # ('c', 3)
print(queue) # {'a': 1, 'b': 2}
empty = {}
try:
empty.popitem()
except KeyError as exc:
print(exc) # 'popitem(): dictionary is empty'clear versus rebinding
clear() empties the dictionary object itself. Assigning {} to the name creates a new object and leaves the old one untouched. The difference shows up when two names refer to the same dictionary.
a = {"x": 1}
b = a
a = {} # rebinds a only
print(b) # {'x': 1}
c = {"x": 1}
d = c
c.clear() # empties the shared object
print(d) # {}Removing by condition
To remove entries that match a condition, building a new dictionary with a comprehension is usually clearer than deleting one by one.
stock = {"apple": 0, "pear": 5, "fig": 0, "kiwi": 2}
in_stock = {k: v for k, v in stock.items() if v > 0}
print(in_stock) # {'pear': 5, 'kiwi': 2}If you must delete from the original, do not delete while looping over it. Loop over list(stock) instead. The pitfalls chapter explains why.
Mutation is shared
A dictionary is a mutable object. Assignment to another name copies the reference, not the contents. Every name bound to the same dictionary sees every change, including changes made inside functions.
a = {"x": 1}
b = a
b["y"] = 2
print(a) # {'x': 1, 'y': 2}
print(a is b) # Truedef add_discount(prices, code):
prices["discount"] = code # modifies the caller's dictionary
order = {"total": 40}
add_discount(order, "SPRING")
print(order) # {'total': 40, 'discount': 'SPRING'}If a function should not alter its argument, copy first with dict(prices) or prices.copy(). These make shallow copies, which share nested objects. The copying chapter covers when that is enough.
Changing values during iteration
You may change the value of an existing key while looping over the dictionary, because the number of keys stays the same.
prices = {"apple": 0.5, "pear": 0.75}
for name in prices:
prices[name] *= 2
print(prices) # {'apple': 1.0, 'pear': 1.5}Adding or removing keys during the loop is different. It changes the size of the dictionary and raises RuntimeError: dictionary changed size during iteration. Treat "values only" as the safe case.
You can see the problem directly.
shared = dict.fromkeys(["a", "b"], [])
shared["a"].append(1)
print(shared) # {'a': [1], 'b': [1]}
separate = {k: [] for k in ["a", "b"]}
separate["a"].append(1)
print(separate) # {'a': [1], 'b': []}Common errors
KeyErroron+=. Augmented assignment reads before it writes. Initialize the key first, or useget()with a default.- Using
update()result.update(),clear()andsetdefault()do not return the dictionary (setdefault()returns a value, not the dictionary). Do not chain them as if they did. - Unhashable keys. Assigning with a list as the key raises
TypeError. Convert it to a tuple first. - Surprise aliasing. Two names, one dictionary. Copy when you need independence.
- Wrong removal call. Use
delorpop(k)when the key must exist, andpop(k, default)when it may not.
Exercise
Predict the output, then explain it. inventory = {"a": 1, "b": 2, "c": 3} inventory["b"] = 20 del inventory["a"] inventory["a"] = 10 print(inventory) print(inventory.popitem())
Show answer
The first print shows {'b': 20, 'c': 3, 'a': 10}. Replacing "b" keeps its position, deleting "a" removes it, and adding "a" again places it at the end. popitem() then removes and returns the last-inserted entry, so it prints ('a', 10).
Exercise
Write a function remove_zeros(d) that deletes every key whose value is 0 from the dictionary d in place and returns how many keys were removed. Do not raise RuntimeError.
Show answer
Loop over a list copy of the keys so the dictionary's size can change safely. def removezeros(d): removed = 0 for key in list(d): if d[key] == 0: del d[key] removed += 1 return removed data = {"a": 0, "b": 4, "c": 0} print(removezeros(data)) # 2 print(data) # {'b': 4}