🐍 Python for Everyone

← Back to the quiz

Chapter 8 Exercises 20 min, hands-on

Exercises: Dictionaries & Sets

How to run these Download starter.py below, then run python3 starter.py.

1 Creating & accessing a dictionary

Given student = {"name": "Maria", "age": 20, "major": "Biology"}, print the student's name and major. Then use .get() to safely print the student's "gpa" with a fallback of "N/A", since "gpa" isn't a key here.

2 Dictionary methods

Given inventory = {"pens": 40, "notebooks": 25}, add a new key "erasers" set to 15. Then use .update() to add "markers": 10 and change "pens" to 35, both in one call. Print the inventory after each step.

3 Looping over a dictionary

Given scores = {"Maria": 88, "Jae": 95, "Tomas": 71}, loop over the dictionary with .items() and print each name and score. Also build a running total of every score and print the average score.

4 Set operations

Given weekday_class = {"Maria", "Jae", "Tomas"} and weekend_class = {"Jae", "Priya"}, print the union, the intersection, and the difference (people in weekday_class but not weekend_class).

5 Nested dictionaries

Given a nested dictionary of student records, print Jae's major, then add a new "gpa" field to Tomas's record set to 3.4, then print Tomas's whole record.

🐞 Task 6 — Debug the Code

This is supposed to tally how many times each fruit appears in the list below, but it crashes with a KeyError. Find and fix the bug.

buggy.py
fruits = ["apple", "banana", "apple", "cherry", "banana", "apple"]
tally = {}
for fruit in fruits:
    tally[fruit] = tally[fruit] + 1
print(tally)

7 Order report

Given a list of orders (each one a dictionary with "id", "amount", and "status" keys), loop through them, and for every order with status "shipped", print its id and add its amount to a running total. Print the total in the form: "Total shipped: $107.25".

← Back to Quiz Practice Bank →