Python Dictionaries · Exercises
Beginner

Python Dictionaries Exercises

4 exercises that build on the Python Dictionaries 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 dictionary stores pairs of keys and values, so you can look up a value by a meaningful key, such as a name or an ID, instead of by its position. By the end you can create a dictionary, read values with [] and get(), add, change and delete entries, loop over keys and values, and count things with a dictionary. You will practise: Update the cafe menu; Predict the stock report; Fix the letter counter; Average grade per student.

0 / 4 completed

Python Dictionaries practice exercises

1. Update the cafe menu

Write code Easy

Change the menu dictionary: add "juice" with the price 2.75, change the price of "coffee" to 2.25, then print how many items the menu has.

Your code
menu = {"tea": 1.5, "coffee": 2.0, "cake": 3.25}

# your code here

2. Predict the stock report

Predict the output Medium

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

Read this code
stock = {"pens": 10, "pads": 4}
stock["pens"] = stock["pens"] - 3
stock["clips"] = 50
print(stock)
print(stock.get("tape", 0), len(stock))
for item in stock:
    print(item)

3. Fix the letter counter

Fix the bug Medium

This code should count how many times each letter appears in word and print {'m': 1, 'i': 4, 's': 4, 'p': 2}, but it crashes with a KeyError. Fix it.

Your code
word = "mississippi"
counts = {}
for letter in word:
    counts[letter] += 1
print(counts)

4. Average grade per student

Write code Hard

grades maps each student to a list of marks. Build a new dictionary averages that maps each name to their average mark rounded to 1 decimal place. Then store the name of the student with the highest average in best and print Top student: <name>.

Your code
grades = {"Asha": [88, 92, 79], "Ben": [65, 70, 58], "Chen": [95, 98, 91]}
averages = {}
best = ""

# fill averages, then find best

Next lessonPython Dictionary Methods

More Python Dictionaries examples · All Python exercises