Practical Aggregation Examples
1. Sales Data Analysis
sales_data = [
{"product": "Laptop", "category": "Electronics", "price": 1000, "quantity": 5},
{"product": "Phone", "category": "Electronics", "price": 500, "quantity": 10},
{"product": "Book", "category": "Literature", "price": 20, "quantity": 50}
]
## Total revenue calculation
def calculate_total_revenue(data):
return sum(item['price'] * item['quantity'] for item in data)
## Category-wise revenue
def category_revenue_breakdown(data):
category_revenue = {}
for item in data:
category = item['category']
revenue = item['price'] * item['quantity']
category_revenue[category] = category_revenue.get(category, 0) + revenue
return category_revenue
graph TD
A[Student Performance Analysis]
A --> B[Average Score]
A --> C[Top Performers]
A --> D[Subject Breakdown]
students = [
{"name": "Alice", "math": 85, "science": 90, "english": 88},
{"name": "Bob", "math": 75, "science": 80, "english": 82},
{"name": "Charlie", "math": 95, "science": 92, "english": 90}
]
## Calculate average scores
def calculate_subject_averages(students):
return {
"math": sum(student['math'] for student in students) / len(students),
"science": sum(student['science'] for student in students) / len(students),
"english": sum(student['english'] for student in students) / len(students)
}
## Find top performers
def find_top_performers(students, subject, top_n=2):
return sorted(students, key=lambda x: x[subject], reverse=True)[:top_n]
3. Inventory Management
Metric |
Calculation Method |
Purpose |
Total Stock |
Sum of quantities |
Inventory level |
Low Stock Items |
Filter items below threshold |
Restocking |
Average Price |
Mean of product prices |
Pricing strategy |
inventory = [
{"name": "Shirt", "price": 25, "quantity": 100},
{"name": "Pants", "price": 50, "quantity": 75},
{"name": "Shoes", "price": 80, "quantity": 50}
]
## Identify low stock items
def find_low_stock_items(inventory, threshold=60):
return [item for item in inventory if item['quantity'] < threshold]
## Calculate total inventory value
def calculate_inventory_value(inventory):
return sum(item['price'] * item['quantity'] for item in inventory)
def transform_and_aggregate(data, transformation_func, aggregation_func):
transformed_data = [transformation_func(item) for item in data]
return aggregation_func(transformed_data)
## Example usage in LabEx Python environment
def normalize_price(item):
return item['price'] / 100
def total_normalized_value(normalized_prices):
return sum(normalized_prices)
5. Error-Robust Aggregation
def safe_aggregation(data, key, default_value=0):
try:
return sum(item.get(key, default_value) for item in data)
except Exception as e:
print(f"Aggregation error: {e}")
return None
Key Takeaways
- Use list comprehensions for concise transformations
- Leverage dictionary methods for flexible aggregations
- Implement error handling for robust data processing
- Choose appropriate aggregation techniques based on data structure
This comprehensive guide demonstrates practical approaches to aggregating and analyzing data in lists of dictionaries, showcasing versatility and efficiency in Python data manipulation.