← Back to Chapter 6 Chapter 6 Practical Exam: Dictionaries
30:00

Chapter 6 Practical Exam

Demonstrate your dictionary mastery!

Problems
3
Difficulty
Medium
Time Limit
30 min
Solved
0/3

Problem 1: Word Counter

Medium

Description

Create a function count_words(text) that takes a string and returns a dictionary with each word as a key and its count as the value.

  • Convert words to lowercase before counting
  • Words are separated by spaces
  • Return an empty dict for empty string

Example

count_words("the cat and the dog") # Returns: {'the': 2, 'cat': 1, 'and': 1, 'dog': 1} count_words("Hello Hello HELLO") # Returns: {'hello': 3} count_words("") # Returns: {}
Your Solution
Test Results
Click "Run Tests" to check...

Hint

Use text.lower().split() to get lowercase words. Loop through and use dict.get(word, 0) + 1 to count.

Problem 2: Grade Calculator

Medium

Description

Create a function calculate_average(grades) that takes a dictionary of student names and their grades (list of numbers) and returns a dictionary with each student's average grade.

  • Round averages to 1 decimal place
  • Return empty dict for empty input
  • Handle students with empty grade lists (average = 0)

Example

grades = {"Alice": [90, 85, 92], "Bob": [78, 82, 80]} calculate_average(grades) # Returns: {'Alice': 89.0, 'Bob': 80.0} calculate_average({"Charlie": []}) # Returns: {'Charlie': 0}
Your Solution
Test Results
Click "Run Tests" to check...

Hint

Use dict comprehension: {name: round(sum(scores)/len(scores), 1) if scores else 0 for name, scores in grades.items()}

Problem 3: Inventory Merger

Medium

Description

Create a function merge_inventory(inv1, inv2) that merges two inventory dictionaries. If an item exists in both, add the quantities together.

  • Return a new dictionary (don't modify originals)
  • Handle empty dictionaries
  • Keys are item names, values are quantities

Example

inv1 = {"apples": 10, "bananas": 5} inv2 = {"bananas": 3, "oranges": 7} merge_inventory(inv1, inv2) # Returns: {'apples': 10, 'bananas': 8, 'oranges': 7} merge_inventory({}, {"item": 5}) # Returns: {'item': 5}
Your Solution
Test Results
Click "Run Tests" to check...

Hint

Start with result = inv1.copy(), then loop through inv2 and add using result[key] = result.get(key, 0) + value.