
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
- Add
"lantern"with a price of12. - Change the price of
"rope"to4. - Delete
"map"(it's sold out). - Use
.get()to look up"compass"with a default of0, and store the answer incompass_price. - Loop over
prices.items()and print each line aspotion costs 5.
- Add
"lantern"with a price of12. - Change the price of
"rope"to4. - Delete
"map"(it's sold out). - Use
.get()to look up"compass"with a default of0, and store the answer incompass_price. - Loop over
prices.items()and print each line aspotion costs 5.
main.py Python sleeping
Press Run to try your code, then Check to test it.