Home › Learn › Python › Dictionaries, tuples, and sets

Dictionaries

Lesson 21 of 40. Look values up by key instead of by position.

A dictionary maps keys to values: stock = {"apple": 3, "pear": 0}. stock["apple"] looks a value up; stock["kiwi"] = 5 adds or replaces an entry; del stock["pear"] removes one. Looking up a key that is not there raises KeyError, so use stock.get("kiwi", 0) when a default is fine, and "kiwi" in stock to ask first.

Keys are usually strings or numbers (anything immutable works); values can be anything. Dictionaries keep the order entries were added, and len() counts the entries.

ages = {"Ann": 31}
ages["Ben"] = 27
print(ages.get("Cai", "unknown"))   # unknown
print("Ann" in ages, len(ages))     # True 2

Your task

Write in_stock(stock, item) that returns True when the item is in the dictionary with a count above zero (and False for missing items, without raising an error), and restock(stock, item, amount) that adds the amount to the item's count, creating the entry if needed, and returns the new count.

Hint 1

stock.get(item, 0) > 0

Hint 2

stock[item] = stock.get(item, 0) + amount, then return stock[item]

Show the solution
def in_stock(stock, item):
    return stock.get(item, 0) > 0


def restock(stock, item, amount):
    stock[item] = stock.get(item, 0) + amount
    return stock[item]

    Runs CPython compiled to WebAssembly in this tab (12 MB download the first time, then cached); nothing is sent anywhere.