Practical Usage Examples
1. Word Frequency Counter
from collections import defaultdict
def count_word_frequency(text):
word_freq = defaultdict(int)
for word in text.split():
word_freq[word] += 1
return dict(word_freq)
text = "python is awesome python is powerful"
result = count_word_frequency(text)
print(result)
2. Grouping Data
students = [
('Alice', 'Math'),
('Bob', 'Physics'),
('Charlie', 'Math'),
('David', 'Physics')
]
def group_students_by_subject(students):
subject_groups = defaultdict(list)
for student, subject in students:
subject_groups[subject].append(student)
return dict(subject_groups)
grouped_students = group_students_by_subject(students)
print(grouped_students)
3. Nested Dictionary Management
def manage_nested_data():
user_data = defaultdict(lambda: defaultdict(int))
user_data['john']['login_count'] += 1
user_data['john']['page_views'] += 5
user_data['sarah']['login_count'] += 1
return dict(user_data)
nested_result = manage_nested_data()
print(nested_result)
4. Graph Adjacency List
def create_graph_adjacency_list():
graph = defaultdict(list)
graph['A'].append('B')
graph['A'].append('C')
graph['B'].append('D')
graph['C'].append('D')
return dict(graph)
adjacency_list = create_graph_adjacency_list()
print(adjacency_list)
Workflow Visualization
graph TD
A[Input Data] --> B{Process with defaultdict}
B -->|Word Frequency| C[Count Occurrences]
B -->|Grouping| D[Organize by Category]
B -->|Nested Data| E[Manage Complex Structures]
B -->|Graph Representation| F[Create Adjacency List]
Common Use Case Comparison
Scenario |
Standard Dict |
defaultdict |
Word Counting |
Requires manual key check |
Automatic initialization |
Grouping Data |
Needs explicit list creation |
Automatic list generation |
Nested Structures |
Complex initialization |
Simple, clean implementation |
- Faster for repeated key access
- Reduces boilerplate code
- Slightly more memory overhead
Error Prevention Example
def safe_data_collection():
try:
collection = defaultdict(list)
collection['categories'].append('technology')
return collection
except Exception as e:
print(f"Error in data collection: {e}")
result = safe_data_collection()
print(result)
At LabEx, we emphasize understanding these practical applications to master defaultdict
in real-world Python programming scenarios.