Practical Sorting Solutions
Real-World Sorting Scenarios
Complex Dictionary Sorting
employees = {
'Alice': {'age': 35, 'salary': 75000, 'department': 'HR'},
'Bob': {'age': 42, 'salary': 85000, 'department': 'IT'},
'Charlie': {'age': 28, 'salary': 65000, 'department': 'Finance'}
}
## Multi-criteria sorting
sorted_employees = dict(sorted(
employees.items(),
key=lambda x: (x[1]['department'], -x[1]['salary'])
))
Advanced Sorting Techniques
Using operator
Module
from operator import itemgetter
## Efficient sorting with itemgetter
sorted_by_salary = dict(
sorted(employees.items(),
key=itemgetter(1, 'salary'),
reverse=True)
)
Method |
Use Case |
Performance |
Flexibility |
sorted() |
Simple sorting |
Moderate |
High |
itemgetter() |
Complex sorting |
Fast |
Medium |
Custom key functions |
Specialized sorting |
Flexible |
Very High |
Sorting Workflow
graph TD
A[Input Dictionary] --> B{Sorting Criteria}
B --> |Single Key| C[Simple Sorting]
B --> |Multiple Criteria| D[Complex Sorting]
B --> |Custom Logic| E[Advanced Sorting]
C --> F[Sorted Result]
D --> F
E --> F
Handling Large Dictionaries
import sys
from heapq import nlargest
## Memory-efficient top N sorting
def top_n_items(dictionary, n=3):
return dict(nlargest(n, dictionary.items(), key=lambda x: x[1]['salary']))
## Demonstrate top 3 highest-paid employees
top_employees = top_n_items(employees)
Specialized Sorting Strategies
Conditional Sorting
def department_specific_sort(employees, department):
return dict(
sorted(
{k: v for k, v in employees.items() if v['department'] == department}.items(),
key=lambda x: x[1]['salary'],
reverse=True
)
)
## Sort only IT department employees
it_employees_sorted = department_specific_sort(employees, 'IT')
At LabEx, we recommend:
- Use built-in sorting methods
- Leverage
operator
module for efficiency
- Implement custom sorting logically
- Consider memory constraints
Best Practices
- Choose appropriate sorting method
- Use type-consistent data
- Optimize for specific use cases
- Handle edge cases gracefully