Dictionaries
A dict maps keys to values: {"apple": 2, "bread": 3} looks up a price by
name instead of by position, the way a list would. prices["apple"] reads the
value stored under the key "apple" - and it throws a KeyError if that key
doesn't exist, so you're always looking up something that's actually there in
this lesson.
sum(x for x in items) totals a generator expression - like a list
comprehension without the brackets, built to be summed (or looped) instead of
collected into a list first.
Sometimes a key might not be there, and a KeyError would be the wrong
behavior. prices.get(key, default) reads a value the same way [] does, but
returns default instead of raising when the key is missing - the safe way to
look something up when you're not sure it exists.
Your task: write total_cost(items, prices), which takes a list of item
names and returns the sum of their prices, looked up in prices. Then write
total_cost_safe(items, prices), doing the same thing but treating any item
not in prices as costing 0 instead of raising.
You'll practice:
- Looking up values in a dict with
[]
- Summing a generator expression
- Falling back to a default with
.get(key, default) when a key might be missing