Practical Sorting Examples
Real-World Sorting Scenarios
graph TD
A[Practical Sorting] --> B[Data Processing]
A --> C[Configuration Management]
A --> D[Performance Optimization]
Example 1: Sorting User Profiles
user_profiles = {
'alice_smith': {'age': 28, 'score': 95},
'bob_jones': {'age': 35, 'score': 88},
'charlie_brown': {'age': 22, 'score': 92}
}
## Sort by age
sorted_by_age = dict(sorted(
user_profiles.items(),
key=lambda x: x[1]['age']
))
## Sort by score
sorted_by_score = dict(sorted(
user_profiles.items(),
key=lambda x: x[1]['score'],
reverse=True
))
Example 2: Configuration Management
server_config = {
'database_host': '192.168.1.100',
'cache_server': '192.168.1.101',
'web_server': '192.168.1.102'
}
## Sort IP addresses
sorted_servers = sorted(
server_config.keys(),
key=lambda x: [int(ip) for ip in server_config[x].split('.')]
)
performance_metrics = {
'api_request': 0.05,
'database_query': 0.2,
'file_processing': 0.1
}
## Identify slowest operations
slowest_operations = dict(
sorted(
performance_metrics.items(),
key=lambda x: x[1],
reverse=True
)
)
Advanced Sorting Techniques
Multi-Level Sorting
complex_data = {
'user1': {'department': 'HR', 'salary': 5000},
'user2': {'department': 'IT', 'salary': 6000},
'user3': {'department': 'HR', 'salary': 4500}
}
## Sort by department, then by salary
sorted_complex = dict(sorted(
complex_data.items(),
key=lambda x: (x[1]['department'], x[1]['salary'])
))
Sorting Best Practices
Technique |
Pros |
Cons |
sorted() |
Flexible |
Creates new list |
lambda sorting |
Powerful |
Can be complex |
operator.itemgetter() |
Efficient |
Less readable |
- Use
key
parameter for complex sorting
- Avoid sorting large dictionaries repeatedly
- Consider generator expressions for memory efficiency
LabEx recommends understanding context-specific sorting requirements for optimal implementation.