Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.
Looking Things Up in a Dictionary
A dictionary maps keys to values. Where a list is "the third item", a dictionary is "the item called price".
item = {"name": "widget", "price": 9.99, "stock": 3}
item["name"] # "widget"
item["price"] # 9.99
"stock" in item # True
len(item) # 3Asking for a key that is not there raises KeyError. When a key might be missing, use .get(), which returns None instead of raising, or a default you choose:
item["colour"] # KeyError: 'colour'
item.get("colour") # None
item.get("colour", "grey") # "grey"That default argument is the whole point of .get(). It replaces this:
if "colour" in item:
colour = item["colour"]
else:
colour = "grey"Your task:
Write stock_level(inventory, product) that returns how many of product are in stock. If the product is not in the dictionary at all, return 0 rather than raising an error.
Example Tests
A product that exists returns its count
Input: {"product":"widget","inventory":{"gizmo":7,"widget":3}}
Expected: 3
A different existing product returns its own count
Input: {"product":"gizmo","inventory":{"gizmo":7,"widget":3}}
Expected: 7
A missing product returns 0 instead of raising KeyError
Input: {"product":"sprocket","inventory":{"widget":3}}
Expected: 0
def stock_level(inventory, product):
"""
Look up a product's stock count.
Args:
inventory: a dict mapping product name -> count
product: the product name to look up
Returns:
The count, or 0 if the product is not in the inventory.
"""
# YOUR CODE HERE
passRun your code to see results
⌘↵ runs against the visible tests