Dictionaries and sets
Look up values by key and find unique items.
A dictionary pairs keys with values. Use stock["tea"] to read a known key. stock.get("tea", 0) supplies a default if the key is missing. Assign to a key to add or update a value.
A set holds unique members and supports tests such as "tea" in drinks. Set order is unspecified. Use sorted() when the order of your printed result matters.
A list can repeat the same value.
Try it yourself
Add "water" to the drinks list and store 8 units of water in the dictionary. Print the number of unique drinks and the stock of water.
Target output
3
8Show a hint
Use drinks.append("water") and stock["water"] = 8 before printing the values.
Output
Ready
Run your code to see the output here.
The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.
Show one solution
drinks = ["tea", "coffee", "tea", "water"]
stock = {"tea": 4, "coffee": 2, "water": 8}
print(len(set(drinks)))
print(stock.get("water", 0))