Learn Without Walls
← Back to Module 8

Module 8: Practice Problems

15 problems to reinforce your understanding of dictionaries and tuples

Problem 1: Create a Dictionary Easy

Create a dictionary called book with the keys "title", "author", and "year". Assign appropriate values. Print each value on its own line.

Use curly braces with key-value pairs separated by colons. Access values with book["key"].
book = {
    "title": "To Kill a Mockingbird",
    "author": "Harper Lee",
    "year": 1960
}
print(book["title"])
print(book["author"])
print(book["year"])

Problem 2: Safe Access with get() Easy

Given the dictionary person = {"name": "Alice", "age": 30}, use get() to print the "email" value with a default of "Not provided".

The get() method takes two arguments: the key and the default value.
person = {"name": "Alice", "age": 30}
email = person.get("email", "Not provided")
print(email)  # Not provided

Problem 3: Add and Update Easy

Start with scores = {"math": 85, "science": 90}. Add a new key "english" with value 88, then update "math" to 92. Print the dictionary.

Use scores["new_key"] = value for both adding and updating.
scores = {"math": 85, "science": 90}
scores["english"] = 88
scores["math"] = 92
print(scores)
# {'math': 92, 'science': 90, 'english': 88}

Problem 4: Loop Through a Dictionary Easy

Given ages = {"Alice": 25, "Bob": 30, "Carol": 28}, loop through the dictionary and print each name and age in the format "Name is X years old".

Use for name, age in ages.items(): to loop over key-value pairs.
ages = {"Alice": 25, "Bob": 30, "Carol": 28}
for name, age in ages.items():
    print(f"{name} is {age} years old")

Problem 5: Create and Unpack Tuples Easy

Create a tuple called point with values (5, 10). Unpack it into variables x and y, then print both.

Use x, y = point to unpack.
point = (5, 10)
x, y = point
print(f"x = {x}, y = {y}")

Problem 6: Word Counter Medium

Write code that counts how many times each word appears in the string "the cat and the dog and the bird". Store the counts in a dictionary and print it.

Split the string with .split(), then loop through the words. Check if each word is already a key in the dictionary.
text = "the cat and the dog and the bird"
counts = {}
for word in text.split():
    if word in counts:
        counts[word] += 1
    else:
        counts[word] = 1
print(counts)
# {'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'bird': 1}

Problem 7: Merge Two Dictionaries Medium

Given defaults = {"color": "blue", "size": 12, "font": "Arial"} and user_prefs = {"color": "red", "bold": True}, merge user_prefs into defaults and print the result.

Use the update() method to merge one dictionary into another.
defaults = {"color": "blue", "size": 12, "font": "Arial"}
user_prefs = {"color": "red", "bold": True}
defaults.update(user_prefs)
print(defaults)
# {'color': 'red', 'size': 12, 'font': 'Arial', 'bold': True}

Problem 8: Nested Dictionary Access Medium

Given the nested dictionary below, print the GPA of the student named Bob.

school = {
    "alice": {"age": 20, "gpa": 3.9},
    "bob": {"age": 21, "gpa": 3.4}
}
Chain the square brackets: school["bob"]["gpa"].
print(school["bob"]["gpa"])  # 3.4

Problem 9: Tuple as Dictionary Key Medium

Create a dictionary that maps coordinate tuples to city names: (40.7, -74.0) to "New York" and (51.5, -0.1) to "London". Look up and print the city at (51.5, -0.1).

Tuples are immutable, so they can be used as dictionary keys. Use the tuple directly as the key.
cities = {
    (40.7, -74.0): "New York",
    (51.5, -0.1): "London"
}
print(cities[(51.5, -0.1)])  # London

Problem 10: Find the Max Value Medium

Given prices = {"apple": 1.20, "banana": 0.50, "cherry": 3.00, "date": 5.50}, find and print the most expensive fruit and its price.

Loop through items() and track the maximum price and its corresponding key.
prices = {"apple": 1.20, "banana": 0.50, "cherry": 3.00, "date": 5.50}

max_fruit = ""
max_price = 0

for fruit, price in prices.items():
    if price > max_price:
        max_price = price
        max_fruit = fruit

print(f"Most expensive: {max_fruit} at ${max_price:.2f}")
# Most expensive: date at $5.50

Problem 11: Swap Variables with Tuples Easy

Given a = 100 and b = 200, swap their values using tuple unpacking (without a temporary variable). Print both values before and after the swap.

Use a, b = b, a to swap.
a = 100
b = 200
print(f"Before: a={a}, b={b}")
a, b = b, a
print(f"After: a={a}, b={b}")
# Before: a=100, b=200
# After: a=200, b=100

Problem 12: Invert a Dictionary Hard

Given grades = {"Alice": "A", "Bob": "B", "Carol": "A", "Dave": "C"}, create a new dictionary that maps each grade to a list of students with that grade.

Loop through the original dictionary. For each grade, check if it is already a key in the new dictionary. If not, start a new list. Then append the student name.
grades = {"Alice": "A", "Bob": "B", "Carol": "A", "Dave": "C"}

by_grade = {}
for student, grade in grades.items():
    if grade not in by_grade:
        by_grade[grade] = []
    by_grade[grade].append(student)

print(by_grade)
# {'A': ['Alice', 'Carol'], 'B': ['Bob'], 'C': ['Dave']}

Problem 13: Contact Book Hard

Build a simple contact book as a dictionary of dictionaries. Each contact should have a name (as the key), and a nested dictionary with "phone" and "email". Add at least 3 contacts, then loop through and print each contact's information.

Create a nested structure: contacts = {"Alice": {"phone": "...", "email": "..."}}. Use items() to loop.
contacts = {
    "Alice": {"phone": "555-0101", "email": "alice@example.com"},
    "Bob": {"phone": "555-0102", "email": "bob@example.com"},
    "Carol": {"phone": "555-0103", "email": "carol@example.com"}
}

for name, info in contacts.items():
    print(f"{name}: {info['phone']} | {info['email']}")

Problem 14: Student Averages Hard

Given the dictionary below, calculate and print each student's average score:

students = {
    "Alice": (90, 85, 92),
    "Bob": (78, 82, 80),
    "Carol": (95, 98, 97)
}
Loop through items(). Use sum() and len() on the tuple of scores to calculate the average.
students = {
    "Alice": (90, 85, 92),
    "Bob": (78, 82, 80),
    "Carol": (95, 98, 97)
}

for name, scores in students.items():
    avg = sum(scores) / len(scores)
    print(f"{name}: {avg:.1f}")
# Alice: 89.0
# Bob: 80.0
# Carol: 96.7

Problem 15: Choose the Right Structure Medium

For each scenario, state whether you would use a list, tuple, or dictionary, and explain why:

  1. Storing RGB color values (red=255, green=128, blue=0)
  2. A shopping cart where items can be added and removed
  3. Mapping country codes to country names
  4. The days of the week
  5. Tracking the number of times each letter appears in a word
  1. Tuple(255, 128, 0) — colors are fixed once defined, and position has meaning (R, G, B)
  2. List — items are added and removed, and order may matter
  3. Dictionary{"US": "United States"} — look up country names by their codes
  4. Tuple("Mon", "Tue", ...) — the days of the week never change
  5. Dictionary{"a": 3, "b": 1} — map each letter to its count
Take the Module 8 Quiz Back to Module 8