Dictionary Exercises
Beginner Exercises
These exercises help practice basic dictionary operations such as counting, merging, inverting, and finding values.
- Count character frequencies in a string
- Merge two dictionaries
- Invert a dictionary (swap keys and values)
- Find the key with the maximum value
- Check if two dictionaries have the same keys and values
Example
# Count character frequencies
text = "hello world"
char_count = {}
for char in text:
if char != " ": # Ignore spaces
char_count[char] = char_count.get(char, 0) + 1
print("Character counts:", char_count)
# Find key with maximum value
ages = {"John": 30, "Jane": 25, "Bob": 35, "Alice": 28}
max_name = max(ages, key=ages.get)
print(f"Oldest person: {max_name} ({ages[max_name]} years)")
Output
Character counts: {'h': 1, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1} Oldest person: Bob (35 years)
Intermediate Challenges
These problems require working with comprehensions, nested access, filtering, and grouping.
Problem | Input Example | Expected Output |
---|---|---|
Word frequency counter | "hello world hello" | {'hello': 2, 'world': 1} |
Dictionary comprehension | [1, 2, 3, 4, 5] | {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} |
Nested dictionary access | {'a': {'b': {'c': 1}}} | 1 |
Filter dictionary by value | {'a': 1, 'b': 2, 'c': 3, 'd': 4}, value > 2 | {'c': 3, 'd': 4} |
Group items by category | [('fruit', 'apple'), ('fruit', 'banana'), ('vegetable', 'carrot')] | {'fruit': ['apple', 'banana'], 'vegetable': ['carrot']} |
Advanced Problems
For advanced practice, try using dictionaries to build caching mechanisms or simulate data structures.
Example
# Implement a simple cache with dictionary
def cached(func):
cache = {}
def wrapper(*args):
if args in cache:
print(f"Cache hit for {args}")
return cache[args]
print(f"Cache miss for {args}")
result = func(*args)
cache[args] = result
return result
return wrapper
@cached
def expensive_function(x):
# Simulate expensive computation
return x * x
print(expensive_function(4))
print(expensive_function(4)) # Should use cache
print(expensive_function(5))
print(expensive_function(5)) # Should use cache
Output
Cache miss for (4,) 16 Cache hit for (4,) 16 Cache miss for (5,) 25 Cache hit for (5,) 25