Python Basics — Dictionaries: Practice Exercises

2 minute read

Dictionaries — Practice Exercises

Test your understanding of dictionary creation, methods, comprehensions, and nested dicts.


Exercise 1 — Word Frequency Counter

Write a function word_freq(text) that returns a dictionary mapping each word to its count. Ignore case.

word_freq("The cat and the dog and the fish")
# {'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'fish': 1}
Show Solution
def word_freq(text):
    words = text.lower().split()
    freq = {}
    for word in words:
        freq[word] = freq.get(word, 0) + 1
    return freq

result = word_freq("The cat and the dog and the fish")
print(result)
# {'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'fish': 1}

Exercise 2 — Merge Two Dictionaries

Write a function merge_dicts(d1, d2) that merges two dictionaries. If both have the same key, the value should be the sum.

merge_dicts({"a": 1, "b": 2}, {"b": 3, "c": 4})
# {'a': 1, 'b': 5, 'c': 4}
Show Solution
def merge_dicts(d1, d2):
    result = d1.copy()
    for key, value in d2.items():
        result[key] = result.get(key, 0) + value
    return result

print(merge_dicts({"a": 1, "b": 2}, {"b": 3, "c": 4}))
# {'a': 1, 'b': 5, 'c': 4}

print(merge_dicts({}, {"x": 10}))
# {'x': 10}

Exercise 3 — Invert a Dictionary

Write a function invert_dict(d) that swaps keys and values. If multiple keys have the same value, group the original keys in a list.

invert_dict({"a": 1, "b": 2, "c": 1})
# {1: ['a', 'c'], 2: ['b']}
Show Solution
def invert_dict(d):
    result = {}
    for key, value in d.items():
        result.setdefault(value, []).append(key)
    return result

print(invert_dict({"a": 1, "b": 2, "c": 1}))
# {1: ['a', 'c'], 2: ['b']}

print(invert_dict({"x": 10, "y": 20, "z": 10}))
# {10: ['x', 'z'], 20: ['y']}

Exercise 4 — Nested Dict Access

Given the following nested dictionary, write code to safely extract the city of the second user. Return "Unknown" if any key is missing.

data = {
    "users": [
        {"name": "Alice", "address": {"city": "New York"}},
        {"name": "Bob", "address": {"city": "London"}}
    ]
}
Show Solution
data = {
    "users": [
        {"name": "Alice", "address": {"city": "New York"}},
        {"name": "Bob", "address": {"city": "London"}}
    ]
}

# Safe access
try:
    city = data["users"][1]["address"]["city"]
except (KeyError, IndexError, TypeError):
    city = "Unknown"

print(city)  # London

# Test with missing data
empty = {}
try:
    city = empty["users"][1]["address"]["city"]
except (KeyError, IndexError, TypeError):
    city = "Unknown"

print(city)  # Unknown

Exercise 5 — Student Grade Report

Given a dictionary of students and their scores, write a function that returns a new dictionary with each student’s average and letter grade.

scores = {
    "Alice": [95, 87, 92],
    "Bob": [78, 65, 82],
    "Charlie": [88, 90, 85]
}

Grading: A (90+), B (80-89), C (70-79), D (60-69), F (<60)

Show Solution
def grade_report(scores):
    def letter_grade(avg):
        if avg >= 90: return "A"
        elif avg >= 80: return "B"
        elif avg >= 70: return "C"
        elif avg >= 60: return "D"
        else: return "F"

    report = {}
    for name, grades in scores.items():
        avg = sum(grades) / len(grades)
        report[name] = {
            "average": round(avg, 1),
            "grade": letter_grade(avg)
        }
    return report

scores = {
    "Alice": [95, 87, 92],
    "Bob": [78, 65, 82],
    "Charlie": [88, 90, 85]
}

result = grade_report(scores)
for name, info in result.items():
    print(f"{name}: {info['average']} ({info['grade']})")
# Alice: 91.3 (A)
# Bob: 75.0 (C)
# Charlie: 87.7 (B)

Scoring Guide

Score Level
5/5 Excellent — dictionaries mastered
3-4/5 Good — review comprehensions and nesting
1-2/5 Keep practicing — re-read the chapter

Next chapter: Sets →

Updated: