Code

The Price Ledger

A dictionary (dict) stores key: value pairs, like words and their meanings. You look things up by key, not by position.

ages = {"Ada": 12, "Bo": 11}
print(ages["Ada"])         # 12
ages["Cy"] = 13            # add a new pair
ages["Bo"] = 12            # update an existing value
del ages["Ada"]            # delete a pair
print("Bo" in ages)        # True (checks keys)

Looking up a missing key with ages["Zed"] crashes with a KeyError. The safe way is .get(), which returns a default instead:

ages.get("Zed", 0)   # 0

To loop over both keys and values, use .items():

for name, age in ages.items():
    print(name, age)

Assignment

  1. Add "lantern" with a price of 12.
  2. Change the price of "rope" to 4.
  3. Delete "map" (it's sold out).
  4. Use .get() to look up "compass" with a default of 0, and store the answer in compass_price.
  5. Loop over prices.items() and print each line as potion costs 5.