
Code
Counting Stock
A shop doesn't keep ten copies of "rope" in a list. It keeps one line that says "rope: 10". In Python, that's a dict that maps each thing to how many you have:
stock = {}
stock["rope"] = stock.get("rope", 0) + 3 # add 3
stock["rope"] = stock.get("rope", 0) + 2 # add 2 more
print(stock) # {'rope': 5}
del stock["rope"] # gone completely
Objects as keys
The keys can be your own objects, if they are hashable. A frozen dataclass is perfect: two equal objects have the same hash, so they land on the same key.
@dataclass(frozen=True)
class Gem:
name: str
value: int
stock = {Gem("Opal", 5): 1}
print(stock[Gem("Opal", 5)]) # 1 (an equal Gem finds it)
This lesson builds the heart of the next boss, so take your time!
Assignment
- Make
Gema frozen dataclass with the fieldsname: strandvalue: int. Shelf.__init__starts an empty dict calledself._stock.count(gem)returns how many ofgemyou have, or0.add(gem, qty=1): ifqtyis0or less, raiseValueError. Otherwise addqtyto the count.remove(gem, qty=1): if you have fewer thanqty, raiseValueError. Otherwise takeqtyaway. When the count reaches0, delete the key fromself._stock.
- Make
Gema frozen dataclass with the fieldsname: strandvalue: int. Shelf.__init__starts an empty dict calledself._stock.count(gem)returns how many ofgemyou have, or0.add(gem, qty=1): ifqtyis0or less, raiseValueError. Otherwise addqtyto the count.remove(gem, qty=1): if you have fewer thanqty, raiseValueError. Otherwise takeqtyaway. When the count reaches0, delete the key fromself._stock.
main.py Python sleeping
Press Run to try your code, then Check to test it.