Looking Things Up in a Dictionary

~8 mincode completion

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.

Examples

A product that exists returns its count

Input
stock_level({"gizmo": 7, "widget": 3}, "widget")
Output
3

A different existing product returns its own count

Input
stock_level({"gizmo": 7, "widget": 3}, "gizmo")
Output
7

A missing product returns 0 instead of raising KeyError

Input
stock_level({"widget": 3}, "sprocket")
Output
0

Hints

Hint 1

A dictionary keyed by the value counts occurrences in one pass.

Hint 2

Watch for this: used bracket lookup without guard.

Requirements

  • inventory: a dict mapping product name -> count

  • product: the product name to look up

  • Return the count, or 0 if the product is not in the inventory.

Constraints

  • Standard library only, no imports required

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~8 min

8 employers weight this skill

3 quant funds, 2 frontier labs, 2 big tech firms, 1 AI product company. Top match scores 80.

Python
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
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.