مشروع: تقرير مبيعات
هذا بالضبط نوع الشغل اللي يسويه محلل البيانات: عندك طلبات، وتبي تطلع منها تقرير فيه الإيرادات لكل تصنيف وأكثر منتج مبيعاً. شغّل الكود وشف كيف تتجمع القوائم والقواميس والدوال والحلقات مع بعض.
PYTHON
orders = [
{"product": "Laptop", "category": "Hardware", "qty": 2, "price": 4800},
{"product": "Router", "category": "Networking", "qty": 5, "price": 420},
{"product": "ERP License", "category": "Software", "qty": 10, "price": 1200},
{"product": "Monitor", "category": "Hardware", "qty": 4, "price": 1100},
{"product": "Router", "category": "Networking", "qty": 3, "price": 420},
{"product": "Antivirus", "category": "Software", "qty": 20, "price": 180},
{"product": "Laptop", "category": "Hardware", "qty": 1, "price": 4800},
]
def revenue(order):
return order["qty"] * order["price"]
by_category = {}
for o in orders:
by_category[o["category"]] = by_category.get(o["category"], 0) + revenue(o)
print("REVENUE BY CATEGORY")
print("-" * 28)
for cat in sorted(by_category, key=lambda c: by_category[c], reverse=True):
print(f"{cat:<14}{by_category[cat]:>10,} SAR")
print("-" * 28)
print(f"{'Total':<14}{sum(by_category.values()):>10,} SAR")انتبه
sorted(..., key=lambda c: by_category[c], reverse=True) ترتب التصنيفات حسب الإيراد من الأعلى للأقل، مثل ORDER BY revenue DESC في SQL.