Python KeyError · Exercises
Core Python

Python KeyError Exercises

4 exercises that build on the Python KeyError: What It Means and How to Fix It lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: A KeyError is raised when you use square brackets to ask a dictionary for a key it does not contain, like user["phone"] when there is no "phone" key. By the end you can read a KeyError and its traceback, track down why a key is missing, and choose the right fix: get(), in, setdefault(), defaultdict or try/except. You will practise: Price with a default; Predict get() and setdefault(); Fix the word counter; Group people by city.

0 / 4 completed

Python KeyError practice exercises

1. Price with a default

Write code Easy

Write get_price(menu, item) that returns the price of item from the dictionary menu, or 0 if the item isn't on the menu. It must never raise a KeyError.

Your code
def get_price(menu, item):
    # return the price, or 0 if item is not in menu
    pass

menu = {"tea": 2.5, "cake": 4.0}
print(get_price(menu, "tea"))
print(get_price(menu, "pizza"))

2. Predict get() and setdefault()

Predict the output Medium

Read the code and type exactly what it will print. Then press Check to compare.

Read this code
stock = {"pen": 3, "ink": 0}
print(stock.get("ink", 5))
print(stock.get("pad", 5))
print("pad" in stock)
stock.setdefault("pad", 10)
stock.setdefault("pen", 99)
print(stock)

3. Fix the word counter

Fix the bug Medium

This code should count how many times each word appears in text and print the dictionary, but it raises KeyError: 'the'. Fix it so counts ends up as {'the': 2, 'cat': 2, 'saw': 1, 'other': 1}.

Your code
text = "the cat saw the other cat"
counts = {}

for word in text.split():
    counts[word] += 1

print(counts)

4. Group people by city

Write code Hard

Write group_by_city(people). It receives a list of dictionaries such as {"name": "Asha", "city": "Pune"} and returns a dictionary mapping each city to a list of names, in the order they appear. Some people have no "city" key: put them under "Unknown". Use get() plus setdefault() or a defaultdict, and avoid any KeyError.

Your code
def group_by_city(people):
    groups = {}
    # add each person's name to the list for their city
    return groups

people = [
    {"name": "Asha", "city": "Pune"},
    {"name": "Ben"},
    {"name": "Chen", "city": "Pune"},
]
print(group_by_city(people))

Next lessonPython IndexError: list index out of range

More Python KeyError: What It Means and How to Fix It examples · All Python exercises