Practical Sorting Examples
Real-World Sorting Scenarios
1. Student Grade Management
students = {
'Alice': {'math': 95, 'physics': 88, 'chemistry': 92},
'Bob': {'math': 85, 'physics': 90, 'chemistry': 87},
'Charlie': {'math': 92, 'physics': 85, 'chemistry': 95}
}
## Sort students by average grade
def calculate_average(grades):
return sum(grades.values()) / len(grades)
sorted_students = dict(sorted(
students.items(),
key=lambda x: calculate_average(x[1]),
reverse=True
))
print(sorted_students)
Sorting Workflow
graph TD
A[Student Grades] --> B{Calculate Average}
B --> C[Sort by Average]
C --> D[Ranked Student List]
2. E-commerce Product Sorting
products = {
'laptop': {'price': 1200, 'stock': 50},
'smartphone': {'price': 800, 'stock': 100},
'tablet': {'price': 500, 'stock': 75}
}
## Multi-criteria sorting
def product_ranking(product):
return (
-product[1]['stock'], ## Descending stock
product[1]['price'] ## Ascending price
)
sorted_products = dict(sorted(
products.items(),
key=product_ranking
))
print(sorted_products)
Sorting Criteria Comparison
Sorting Method |
Criteria |
Use Case |
Single Key |
Simple comparison |
Basic sorting |
Multiple Keys |
Complex ranking |
Advanced selection |
Custom Function |
Flexible logic |
Specialized sorting |
3. Log Analysis Sorting
system_logs = {
'2023-05-01': {'errors': 5, 'warnings': 10},
'2023-04-30': {'errors': 3, 'warnings': 15},
'2023-05-02': {'errors': 8, 'warnings': 7}
}
## Sort logs by total issue count
def total_issues(log_entry):
return log_entry[1]['errors'] + log_entry[1]['warnings']
sorted_logs = dict(sorted(
system_logs.items(),
key=total_issues,
reverse=True
))
print(sorted_logs)
Advanced Sorting Techniques
def complex_sort(dictionary, primary_key, secondary_key=None):
if secondary_key:
return dict(sorted(
dictionary.items(),
key=lambda x: (x[1][primary_key], x[1][secondary_key])
))
return dict(sorted(
dictionary.items(),
key=lambda x: x[1][primary_key]
))
Key Takeaways
- Leverage lambda functions for flexible sorting
- Use custom key functions for complex comparisons
- Consider multiple sorting criteria
At LabEx, we recommend mastering these practical sorting techniques to handle diverse data manipulation challenges in Python.