Welcome to Day 35 of your Python journey!
After diving deep into lists, dictionaries, sets, comprehensions, and modules like itertools
and collections
, it’s time to put your knowledge to the test.
Let’s solve a fun and practical data structure challenge! 💡
🎯 Challenge Overview
You’re given a list of orders placed on an online store. Each order contains:
- Customer name
- Product name
- Quantity
- Price per unit
Your task is to:
- Calculate the total amount spent by each customer.
- Find the top 3 products based on total quantity sold.
- Show the most valuable single order (by total value).
📦 Sample Data
orders = [ {'customer': 'Alice', 'product': 'Pen', 'quantity': 3, 'price': 5}, {'customer': 'Bob', 'product': 'Notebook', 'quantity': 2, 'price': 15}, {'customer': 'Alice', 'product': 'Notebook', 'quantity': 1, 'price': 15}, {'customer': 'Dave', 'product': 'Pen', 'quantity': 10, 'price': 5}, {'customer': 'Carol', 'product': 'Pen', 'quantity': 1, 'price': 5}, {'customer': 'Bob', 'product': 'Pen', 'quantity': 2, 'price': 5}, {'customer': 'Alice', 'product': 'Pencil', 'quantity': 5, 'price': 2}, ]
🛠️ Step-by-Step Solution
✅ 1. Total Amount Spent by Each Customer
from collections import defaultdict customer_totals = defaultdict(float) for order in orders: name = order['customer'] total = order['quantity'] * order['price'] customer_totals[name] += total print("💰 Total spent by each customer:") for customer, total in customer_totals.items(): print(f"{customer}: ₹{total}")
✅ 2. Top 3 Products by Quantity Sold
from collections import Counter product_counter = Counter() for order in orders: product_counter[order['product']] += order['quantity'] print("\n📦 Top 3 products sold:") for product, qty in product_counter.most_common(3): print(f"{product}: {qty} units")
✅ 3. Most Valuable Single Order
max_order = max(orders, key=lambda o: o['quantity'] * o['price']) print("\n💎 Most valuable order:") print(max_order)
🔎 Output Example
💰 Total spent by each customer: Alice: ₹40.0 Bob: ₹45.0 Dave: ₹50.0 Carol: ₹5.0 📦 Top 3 products sold: Pen: 16 units Pencil: 5 units Notebook: 3 units 💎 Most valuable order: {'customer': 'Dave', 'product': 'Pen', 'quantity': 10, 'price': 5}
🧠 Concepts Reviewed
-
defaultdict
for grouped totals -
Counter
for frequency counting -
max()
with custom key - Looping and dictionary access
- Clean, readable logic
🧪 Try This Extension
- Sort the customers by total spending.
- Show total revenue per product.
- Return top customers who spent more than ₹40.
Top comments (0)