Changing a dictionary
🌍 In real life. A shopkeeper's stock book changes all day: a new item gets its own line, a sold item's count goes down, and a discontinued item's line is crossed out. When someone asks about an item that isn't in the book, a polite shopkeeper says "we have 0" instead of shouting.
Dictionaries change the same way, and they have a polite way to ask too.
The idea in one sentence: d[key] = value adds or changes a pair, del d[key] removes one, and get and pop read and remove without crashing on a missing key.
Its words:
d[key] = value: adds a new pair, or changes the value if the key existsdel d[key]: removes a paird.get(key, default): the value, ordefault(orNone) if the key is missingd.pop(key): removes the pair and gives back its valued.update(other),d.setdefault(key, value): change several at once, or add only if missing
Step by step, for the lockers below:
ages["Cy"] = 7: there's no "Cy" locker, so a new one is added.ages["Bo"] = 12: "Bo" exists, so its value changes from 11 to 12.del ages["Ana"]: the "Ana" locker is removed.
ages = {"Ana": 9, "Bo": 11}
ages["Cy"] = 7
ages["Bo"] = 12
del ages["Ana"]
print(ages)Two gentler ways to read and remove:
d.get(key)gives the value, orNoneif the key isn't there. No error!d.get(key, default)givesdefaultinstead ofNone.d.pop(key)removes the pair and gives back its value.
ages = {"Ana": 9, "Bo": 11}
print(ages.get("Zed"))
print(ages.get("Zed", 0))
print(ages.pop("Bo"))
print(ages)Changing several at once. d.update(other) copies every key of other into d, adding new ones and overwriting ones already there. d.setdefault(key, value) adds the key only if it is missing, and gives back the value that ends up stored, so it never overwrites.
ages = {"Ana": 9, "Bo": 11}
ages.update({"Bo": 12, "Cy": 8})
print(ages)
print(ages.setdefault("Ana", 0), ages.setdefault("Di", 0))
print(ages)Merging into a new dictionary. update changes the dictionary itself. To build a new merged dictionary and keep both old ones, write a | b (Python 3.9 and later) or {**a, **b}, where ** unpacks a dictionary's pairs into the new one. When both have the same key, the right-hand one wins. a |= b does the same as a.update(b).
prices = {"tea": 15, "singara": 10}
today = {"tea": 20, "puri": 5}
print(prices | today)
print({**prices, **today, "water": 10})
print(prices)What it costs. Adding, changing, removing and get each go straight to one locker by the key's hash, so each takes about the same time however big the dictionary is.
Mistakes and edge cases.
- Adding to a missing key.
d["x"] += 1on a new key givesKeyError: 'x': Python must read the old value first. Writed["x"] = d.get("x", 0) + 1. - Removing a missing key.
del d["z"]andd.pop("z")both giveKeyError: 'z'.d.pop("z", None)doesn't. - Adding while looping. Changing a dictionary's keys inside
for k in d:givesRuntimeError: dictionary changed size during iteration. Loop overlist(d)instead. - get() hides typos.
d.get("Boo")quietly givesNone, so a misspelt key can go unnoticed.
Quiz
What does this print?
d = {"a": 1} d["b"] = 2 d["a"] = 5 print(d)What does this print?
d = {"a": 1} print(d.get("z"))What does this print?
d = {"a": 1} print(d.get("z", 0))What does this print?
d = {"a": 1, "b": 2} x = d.pop("a") print(x, d)Which one never stops with a KeyError?
- d.get(key)
- del d[key]
- d[key]
Which line stops this program with an error?
stock = {"pen": 5} stock["pen"] = stock["pen"] + 1 stock["book"] = stock["book"] + 1 print(stock)
Coding tasks
Start with
stock = {"pens": 5}. Add"books"with the value 3, change"pens"to 4, then printstock.Word scores are
scores = {"cat": 3, "dog": 2, "fish": 5}. Ask for a word and print its score, or 0 if it has none. Useget().Start with
book = {"Ana": "123", "Bo": "456"}. Ask for a name. If it's in the book, remove it. If not, printnot found. Either way, printbookat the end.