Python 3D Academyবাংলা

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 exists
  • del d[key]: removes a pair
  • d.get(key, default): the value, or default (or None) if the key is missing
  • d.pop(key): removes the pair and gives back its value
  • d.update(other), d.setdefault(key, value): change several at once, or add only if missing

Step by step, for the lockers below:

  1. ages["Cy"] = 7: there's no "Cy" locker, so a new one is added.
  2. ages["Bo"] = 12: "Bo" exists, so its value changes from 11 to 12.
  3. 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, or None if the key isn't there. No error! d.get(key, default) gives default instead of None.
  • 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"] += 1 on a new key gives KeyError: 'x': Python must read the old value first. Write d["x"] = d.get("x", 0) + 1.
  • Removing a missing key. del d["z"] and d.pop("z") both give KeyError: 'z'. d.pop("z", None) doesn't.
  • Adding while looping. Changing a dictionary's keys inside for k in d: gives RuntimeError: dictionary changed size during iteration. Loop over list(d) instead.
  • get() hides typos. d.get("Boo") quietly gives None, so a misspelt key can go unnoticed.

Quiz

  1. What does this print?

    d = {"a": 1}
    d["b"] = 2
    d["a"] = 5
    print(d)
  2. What does this print?

    d = {"a": 1}
    print(d.get("z"))
  3. What does this print?

    d = {"a": 1}
    print(d.get("z", 0))
  4. What does this print?

    d = {"a": 1, "b": 2}
    x = d.pop("a")
    print(x, d)
  5. Which one never stops with a KeyError?

    • d.get(key)
    • del d[key]
    • d[key]
  6. 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

  1. Start with stock = {"pens": 5}. Add "books" with the value 3, change "pens" to 4, then print stock.

  2. Word scores are scores = {"cat": 3, "dog": 2, "fish": 5}. Ask for a word and print its score, or 0 if it has none. Use get().

  3. Start with book = {"Ana": "123", "Bo": "456"}. Ask for a name. If it's in the book, remove it. If not, print not found. Either way, print book at the end.