MyMisPal
← Python lessons
Lesson 13 of 13

Project: a sales report

This is exactly the kind of work a data analyst does: you have orders and need a report with revenue per category and the best-selling product. Run the code and see lists, dictionaries, functions and loops working together.

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")
Watch outsorted(..., key=lambda c: by_category[c], reverse=True) orders categories by revenue, highest first, like ORDER BY revenue DESC in SQL.

Exercises

Exercise 1

Using the same orders (already in the editor), print the average order value with two decimals.

Exercise 2

Print the name of the product with the highest total quantity sold (add up quantities per product first).

Spotted a mistake on this page, or have an idea to improve the site?