Practical Examples
Real-World Sorting Scenarios
students = {
'Alice': {'score': 85, 'age': 22},
'Bob': {'score': 92, 'age': 20},
'Charlie': {'score': 78, 'age': 23}
}
## Sort students by score in descending order
sorted_by_performance = dict(
sorted(students.items(),
key=lambda x: x[1]['score'],
reverse=True)
)
2. Inventory Management
inventory = {
'laptop': {'quantity': 50, 'price': 1000},
'smartphone': {'quantity': 100, 'price': 500},
'tablet': {'quantity': 25, 'price': 300}
}
## Sort by quantity in ascending order
low_stock_first = dict(
sorted(inventory.items(),
key=lambda x: x[1]['quantity'])
)
3. Word Frequency Analysis
word_count = {
'python': 45,
'javascript': 30,
'java': 55,
'c++': 20
}
## Sort programming languages by usage frequency
sorted_by_popularity = dict(
sorted(word_count.items(),
key=lambda x: x[1],
reverse=True)
)
Sorting Strategies Flowchart
graph TD
A[Sorting Dictionary] --> B{Sorting Criteria}
B -->|By Keys| C[Key-Based Sorting]
B -->|By Values| D[Value-Based Sorting]
B -->|Nested Values| E[Complex Sorting]
C --> F[Simple Ordering]
D --> G[Performance Optimization]
E --> H[Advanced Filtering]
Sorting Method |
Use Case |
Time Complexity |
sorted(dict.items()) |
Simple sorting |
O(n log n) |
collections.OrderedDict |
Maintaining order |
O(1) |
Custom key functions |
Complex sorting |
O(n log n) |
4. Dynamic Configuration Management
config = {
'database': {'connections': 5, 'priority': 2},
'cache': {'connections': 10, 'priority': 1},
'api': {'connections': 3, 'priority': 3}
}
## Sort by connection priority
sorted_by_priority = dict(
sorted(config.items(),
key=lambda x: x[1]['priority'])
)
LabEx Optimization Technique
def smart_sort(dictionary, key_func, reverse=False):
"""
Advanced sorting method for complex dictionaries
Optimized for LabEx data processing
"""
return dict(sorted(
dictionary.items(),
key=key_func,
reverse=reverse
))
## Example usage
result = smart_sort(
students,
key_func=lambda x: x[1]['score'],
reverse=True
)
Key Takeaways
- Use
sorted()
with dict()
to preserve dictionary structure
- Leverage lambda functions for complex sorting
- Consider performance implications for large datasets
- Choose sorting strategy based on specific use case