Challenges
Challenge: Word Frequency Counter
Create a function that counts the frequency of each word in a text string and returns the result as a dictionary where keys are the unique words found in the text and values are the number of times each word appears.
Requirements:
- Convert all words to lowercase
- Remove punctuation from words
- Ignore empty strings
Example:
text = "Hello world! Hello Python." result = word_frequency(text) print(result) # Output: {'hello': 2, 'world': 1, 'python': 1}
Visualization Explained:
The visualization on the right shows your dictionary as it's being built. Each key-value pair is represented, making it easy to see how your dictionary evolves as your code executes.
Dictionary Resources
Dictionary Methods
Complete reference of all Python dictionary methods with examples
Dictionary Performance
Understanding time complexity and performance optimization
Dictionary Best Practices
Coding standards and best practices for using dictionaries
Advanced Dictionary Techniques
Learn about defaultdict, Counter, and OrderedDict
Dictionary Methods Reference
dict.get(key[, default])
Returns the value for key if key is in the dictionary, else default.
user = {'name': 'John', 'age': 30} print(user.get('email', 'Not found'))
dict.items()
Returns a view object that displays a list of dictionary's (key, value) tuple pairs.
user = {'name': 'John', 'age': 30} for key, value in user.items(): print(key, value)
dict.keys()
Returns a view object that displays a list of all the keys.
user = {'name': 'John', 'age': 30} print(list(user.keys()))
dict.values()
Returns a view object that displays a list of all the values.
user = {'name': 'John', 'age': 30} print(list(user.values()))
dict.update([other])
Updates the dictionary with the key/value pairs from other.
user = {'name': 'John'} user.update({'age': 30, 'city': 'NYC'}) print(user)
dict.pop(key[, default])
Removes and returns the value for key. If key is not found, default is returned.
user = {'name': 'John', 'age': 30} age = user.pop('age') email = user.pop('email', None)
Common Dictionary Patterns
Dictionary Comprehension
A concise way to create dictionaries using an expression.
# Create a dictionary of squares numbers = [1, 2, 3, 4, 5] squares = {num: num**2 for num in numbers} print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # Dictionary comprehension with condition even_squares = {num: num**2 for num in numbers if num % 2 == 0} print(even_squares) # {2: 4, 4: 16}
Counting with Dictionaries
Using dictionaries to count occurrences (the basis of the current challenge).
# Method 1: Manual counting text = "apple banana apple orange banana apple" counts = {} for word in text.split(): counts[word] = counts.get(word, 0) + 1 print(counts) # {'apple': 3, 'banana': 2, 'orange': 1} # Method 2: Using collections.Counter from collections import Counter counts = Counter(text.split()) print(dict(counts)) # {'apple': 3, 'banana': 2, 'orange': 1}
Nested Dictionaries
Using dictionaries to represent hierarchical data structures.
# Creating a nested dictionary person = { 'name': 'John', 'age': 30, 'address': { 'city': 'New York', 'zip': '10001', 'coordinates': { 'lat': 40.7128, 'lng': -74.0060 } }, 'skills': ['Python', 'JavaScript'] } # Accessing nested values print(person['address']['city']) # New York print(person['address']['coordinates']['lat']) # 40.7128 # Safe access with get() for nested dictionaries city = person.get('address', {}).get('city', 'Unknown') print(city) # New York
Dictionary Merging
Different ways to combine dictionaries.
# Method 1: Using update() dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} merged = dict1.copy() # Create a copy to avoid modifying original merged.update(dict2) print(merged) # {'a': 1, 'b': 3, 'c': 4} # Method 2: Using unpacking (Python 3.5+) dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} merged = {**dict1, **dict2} # Later values override earlier ones print(merged) # {'a': 1, 'b': 3, 'c': 4} # Method 3: Using | operator (Python 3.9+) dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} merged = dict1 | dict2 # Similar to unpacking print(merged) # {'a': 1, 'b': 3, 'c': 4}