Practical Grouping Methods
Advanced Grouping Techniques
1. Grouping with Collections Module
from collections import defaultdict
def group_transactions_by_category(transactions):
categorized = defaultdict(list)
for transaction in transactions:
categorized[transaction['category']].append(transaction)
return dict(categorized)
transactions = [
{'id': 1, 'category': 'food', 'amount': 50},
{'id': 2, 'category': 'transport', 'amount': 30},
{'id': 3, 'category': 'food', 'amount': 45},
]
grouped_transactions = group_transactions_by_category(transactions)
print(grouped_transactions)
2. Functional Approach with Lambda
def group_by_custom_criteria(items, criteria):
return {
key: [item for item in items if criteria(item, key)]
for key in set(criteria(item, None) for item in items)
}
## Example: Grouping numbers by divisibility
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
grouped_numbers = group_by_custom_criteria(
numbers,
lambda num, divisor: num % 3 == 0
)
print(grouped_numbers)
Specialized Grouping Scenarios
Nested Grouping
def nested_grouping(data):
result = {}
for item in data:
primary_key = item['department']
secondary_key = item['role']
if primary_key not in result:
result[primary_key] = {}
if secondary_key not in result[primary_key]:
result[primary_key][secondary_key] = []
result[primary_key][secondary_key].append(item)
return result
employees = [
{'name': 'Alice', 'department': 'HR', 'role': 'Manager'},
{'name': 'Bob', 'department': 'IT', 'role': 'Developer'},
{'name': 'Charlie', 'department': 'HR', 'role': 'Coordinator'},
]
nested_result = nested_grouping(employees)
print(nested_result)
Grouping Method |
Time Complexity |
Memory Efficiency |
defaultdict |
O(n) |
High |
Dictionary Comprehension |
O(n) |
Moderate |
Nested Grouping |
O(nยฒ) |
Low |
Visualization of Grouping Process
graph TD
A[Input List] --> B{Grouping Criteria}
B --> |Department| C[Grouped by Department]
B --> |Role| D[Grouped by Role]
B --> |Custom Logic| E[Complex Grouping]
LabEx Practical Tips
When working with complex grouping scenarios, LabEx recommends:
- Use appropriate data structures
- Consider memory constraints
- Test with various input sizes
Error Handling in Grouping
def safe_group_by(items, key_func):
try:
return {
key: [item for item in items if key_func(item) == key]
for key in set(key_func(item) for item in items)
}
except Exception as e:
print(f"Grouping error: {e}")
return {}
Key Takeaways
- Understand different grouping techniques
- Choose methods based on specific requirements
- Optimize for performance and readability