Practical Use Cases
1. Counting and Grouping
## Count word frequencies
words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'date']
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
## Result: {'apple': 2, 'banana': 2, 'cherry': 1, 'date': 1}
2. Nested Data Processing
## Complex data transformation
students = [
{"name": "Alice", "grades": [85, 90, 92]},
{"name": "Bob", "grades": [78, 85, 80]}
]
student_averages = {
student['name']: sum(student['grades']) / len(student['grades'])
for student in students
}
Configuration Management
3. Application Settings
## Application configuration
app_config = {
"database": {
"host": "localhost",
"port": 5432,
"username": "admin"
},
"logging": {
"level": "INFO",
"file": "/var/log/app.log"
}
}
Caching and Memoization
4. Function Result Caching
def fibonacci_cache(n, cache={}):
if n in cache:
return cache[n]
if n <= 1:
return n
cache[n] = fibonacci_cache(n-1) + fibonacci_cache(n-2)
return cache[n]
5. Complex Mapping Operations
## Mapping between different data representations
employee_data = {
"001": {"name": "John", "department": "IT"},
"002": {"name": "Jane", "department": "HR"}
}
employee_ids = {
emp_data['name']: emp_id
for emp_id, emp_data in employee_data.items()
}
Dictionary Use Case Flow
graph TD
A[Dictionary Use Cases] --> B[Data Counting]
A --> C[Configuration Management]
A --> D[Caching]
A --> E[Data Transformation]
Use Case |
Time Complexity |
Space Complexity |
Counting |
O(n) |
O(k), k = unique items |
Caching |
O(1) lookup |
O(n) storage |
Transformation |
O(n) |
O(n) |
Advanced Techniques
6. Default Dictionary
from collections import defaultdict
## Automatic initialization of values
word_groups = defaultdict(list)
words = ['apple', 'banana', 'cherry', 'date']
for word in words:
word_groups[len(word)].append(word)
## Result: {5: ['apple'], 6: ['banana', 'cherry'], 4: ['date']}
Real-world Applications
- Web development (routing, sessions)
- Data analysis
- Configuration management
- Caching mechanisms
- Text processing
LabEx Recommendation
At LabEx, we emphasize understanding these practical dictionary use cases to write more efficient and readable Python code.