Practical Use Cases
Real-World Dictionary Applications
Dictionaries are versatile data structures with numerous practical applications across various domains of software development.
def aggregate_student_scores(student_data):
aggregated_scores = {}
for student in student_data:
aggregated_scores[student['name']] = {
'total_score': sum(student['scores']),
'average_score': sum(student['scores']) / len(student['scores'])
}
return aggregated_scores
students = [
{'name': 'Alice', 'scores': [85, 90, 92]},
{'name': 'Bob', 'scores': [75, 80, 85]}
]
result = aggregate_student_scores(students)
print(result)
2. Configuration Management
def merge_configurations(default_config, user_config):
return {**default_config, **user_config}
default_settings = {
'theme': 'light',
'font_size': 12,
'notifications': True
}
user_settings = {
'theme': 'dark',
'language': 'en'
}
final_config = merge_configurations(default_settings, user_settings)
print(final_config)
3. Caching and Memoization
def memoize_fibonacci(func):
cache = {}
def wrapper(n):
if n not in cache:
cache[n] = func(n)
return cache[n]
return wrapper
@memoize_fibonacci
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(100)) ## Efficient calculation
4. Data Grouping and Categorization
def categorize_expenses(transactions):
expense_categories = {}
for transaction in transactions:
category = transaction['category']
amount = transaction['amount']
expense_categories[category] = expense_categories.get(category, 0) + amount
return expense_categories
transactions = [
{'category': 'food', 'amount': 50},
{'category': 'transport', 'amount': 30},
{'category': 'food', 'amount': 40}
]
categorized_expenses = categorize_expenses(transactions)
print(categorized_expenses)
5. API Response Processing
def process_api_response(response):
processed_data = {}
for item in response:
processed_data[item['id']] = {
'name': item['name'],
'status': item.get('active', False)
}
return processed_data
api_response = [
{'id': 1, 'name': 'Product A', 'active': True},
{'id': 2, 'name': 'Product B'}
]
processed_response = process_api_response(api_response)
print(processed_response)
Use Case Complexity Levels
graph TD
A[Dictionary Use Cases] --> B[Basic Aggregation]
A --> C[Intermediate Transformation]
A --> D[Advanced Caching]
A --> E[Complex Data Processing]
Use Case |
Complexity |
Performance Consideration |
Data Aggregation |
Low |
O(n) time complexity |
Caching |
Medium |
Reduced computational overhead |
API Processing |
High |
Depends on input size |
Best Practices
- Choose appropriate dictionary operations
- Consider memory efficiency
- Use type hints and docstrings
- Handle potential edge cases
LabEx recommends mastering these practical techniques to leverage dictionaries effectively in real-world Python programming scenarios.