Exercises — Dictionaries
Exercise 4.4.1 Beginner
Section titled “Exercise 4.4.1 Beginner”Given a list of words, return a dictionary mapping each word to its length.
words = ["apple", "banana", "cherry", "date"]# expected: {"apple": 5, "banana": 6, "cherry": 6, "date": 4}Exercise 4.4.2 Beginner
Section titled “Exercise 4.4.2 Beginner”Given two dictionaries, return a new dictionary that merges them. If a key appears in both, the value from the second dict wins.
a = {"x": 1, "y": 2}b = {"y": 99, "z": 3}# expected: {"x": 1, "y": 99, "z": 3}Exercise 4.4.3 Intermediate
Section titled “Exercise 4.4.3 Intermediate”Given a list of strings, use defaultdict to group them by their first character.
words = ["apple", "avocado", "banana", "blueberry", "cherry"]# expected: {"a": ["apple", "avocado"], "b": ["banana", "blueberry"], "c": ["cherry"]}Exercise 4.4.4 Intermediate
Section titled “Exercise 4.4.4 Intermediate”Given a sentence, use Counter to find the three most common characters (ignoring spaces).
sentence = "the quick brown fox jumps over the lazy dog"# expected: something like [("o", 4), ("e", 3), ("t", 2)]# (exact result depends on the sentence)Exercise 4.4.5 Intermediate
Section titled “Exercise 4.4.5 Intermediate”Given a dictionary mapping student names to lists of grades, return a new dictionary mapping each student to their average grade, rounded to one decimal place.
grades = { "Alice": [90, 85, 92], "Bob": [70, 75, 80], "Carol": [88, 95, 91],}# expected: {"Alice": 89.0, "Bob": 75.0, "Carol": 91.3}Exercise 4.4.6 Advanced
Section titled “Exercise 4.4.6 Advanced”Given a list of dictionaries representing transactions, return a summary dict that maps each category to the total amount spent in that category.
transactions = [ {"category": "food", "amount": 12.5}, {"category": "transport", "amount": 3.0}, {"category": "food", "amount": 8.0}, {"category": "books", "amount": 25.0}, {"category": "transport", "amount": 2.5},]# expected: {"food": 20.5, "transport": 5.5, "books": 25.0}