Dictionary Practice Problems
Apply your knowledge of Python dictionaries with these hands-on exercises. Each problem is designed to test a specific concept, from basic operations to more advanced patterns like comprehensions and default handling.
1. Word Frequency Counter
Task: Write a program that counts the frequency of each word in a given list. The output should be a dictionary where keys are the words and values are their counts.
Hint: Use the .get()
method with a default value to simplify your loop.
Pyground
Count how many times each word appears in the list ['ai', 'python', 'ai', 'ml', 'python', 'ai'].
Expected Output:
{'ai': 3, 'python': 2, 'ml': 1}
Output:
2. Inverting a Dictionary
Task: Given a dictionary, create a new dictionary where the keys and values are swapped. Assume that all values in the original dictionary are unique and hashable.
Pyground
Invert the dictionary {'India': 'IN', 'Canada': 'CA', 'Japan': 'JP'} to map country codes back to country names.
Expected Output:
{'IN': 'India', 'CA': 'Canada', 'JP': 'Japan'}
Output:
3. Merging User Preferences
Task: A user has a set of default preferences. They also provide their own set of overrides. Merge the two dictionaries so that the user’s overrides take precedence over the defaults.
Pyground
Merge a `default_prefs` dictionary with a `user_prefs` dictionary.
Expected Output:
{'theme': 'dark', 'notifications': 'enabled', 'language': 'fr'}
Output:
4. Grouping Data with setdefault
Task: You have a list of tuples, where each tuple contains a category and an item belonging to that category. Group all items by their category into a dictionary.
Pyground
Group a list of students by their house.
Expected Output:
{'Gryffindor': ['Harry', 'Hermione'], 'Slytherin': ['Draco', 'Pansy'], 'Ravenclaw': ['Luna']}
Output:
5. Filtering a Dictionary with a Comprehension
Task: Given a dictionary of product prices, create a new dictionary containing only the products that are on sale (i.e., price is less than 50).
Pyground
Filter the prices dictionary to find all items with a price less than 50.
Expected Output:
{'apple': 20, 'banana': 10, 'orange': 30}
Output:
6. Using defaultdict
for Tallying
Task: Repeat the word frequency counting exercise, but this time, use collections.defaultdict
to make the code even simpler.
Pyground
Use `defaultdict(int)` to tally the quantities of fruits from a list.
Expected Output:
{'apple': 3, 'banana': 2, 'pear': 1}