lesson 37 Dictionaries & Sets · beginner
Add, update and remove pairs
d[key] = value adds a new pair or replaces the old value. del d[key] removes a pair. Updating a key that isn't there raises KeyError.
You'll be able to
- Add or replace a value with
d[key] = value, and remove a pair withdel - Update a value from its old value, with
d[key] = d[key] - nord[key] -= n - Apply a list of events to a dictionary, skipping keys that don't exist
The idea
Stock levels, latest prices and current addresses all change, and a dictionary changes with them, in place, like a list.
stock["P0164"] = 25adds the pair if the key is new and replaces the value if it isn't. There is no separate add command.del stock["P0659"]removes a pair.stock["P0607"] = stock["P0607"] - 2updates a value from its old value. The short formstock["P0607"] -= 2does the same, and+=adds.
Run each example to see what it prints. Running examples doesn't count toward progress.
example-1.py · Keeping stock levels current
stock = {"P0607": 12, "P0208": 3, "P0659": 0}
stock["P0607"] = stock["P0607"] - 2
stock["P0164"] = 25
del stock["P0659"]
print(stock)
stock["P0208"] += 5
print(stock["P0208"], len(stock))example-2.py · Updating a key that isn't there
stock = {"P0607": 12}
stock["P0607"] -= 1
print(stock)
stock["P0123"] -= 1In a real system, changes arrive as a list of events, such as sales. Apply them one at a time, check that each key exists, and react when a value crosses a limit.
example-3.py · Applying a day's sales
stock = {"P0607": 12, "P0208": 3, "P0659": 7}
sales = [("P0607", 2), ("P0208", 2), ("P0123", 1), ("P0659", 5)]
for product_id, quantity in sales:
if product_id not in stock:
print("no such product:", product_id)
continue
stock[product_id] = stock[product_id] - quantity
if stock[product_id] < 3:
print("reorder", product_id, "only", stock[product_id], "left")
print(stock)When to use it: whenever values per key change over time: stock, latest status, the newest email address. Mistakes to avoid:
- Using
+=or-=on a key that may not exist yet. - Expecting
d[key] = valueto fail for an existing key. It silently replaces the value. - Deleting a key that isn't there, which also raises KeyError.
Review
d[key] = valueadds a new pair or replaces the value of an existing key.del d[key]removes a pair.d[key] -= nandd[key] += nread the old value first, so the key must exist.- Apply events one at a time, check keys with
in, and usecontinueto skip the unknown ones. - Next: walk every key and value of a dictionary to answer questions about all of it.
Practise this