Project: analyse sales from a CSV with Python

Read a CSV file, total it, group it by category and find the best-selling product. With an interactive analyser to try it with your own data.

What you will build

A script that opens a sales CSV and answers questions: how much was billed? which category sells most? what is the star product? The ideal project to practise files, loops and dictionaries.

The sample CSV has columns fecha, producto, categoria, unidades, precio. Edit it if you like and press a button:

Step 1: read the CSV

The csv module ships with Python. DictReader turns each row into a dictionary using the header as keys.

import csv

with open("ventas.csv", encoding="utf-8") as f:
    filas = list(csv.DictReader(f))

print(f"Se han leído {len(filas)} filas")
print(filas[0])   # {'fecha': '2024-01-03', 'producto': 'Teclado', ...}

Step 2: the sales total

Each row bills units × price. We add them all up with a generator expression.

total = sum(
    int(fila["unidades"]) * float(fila["precio"])
    for fila in filas
)
print(f"Total facturado: {total:.2f} €")

Step 3: group by category with a dictionary

A dictionary category → running total. dict.get(key, 0) avoids the error when the category doesn't exist yet.

por_categoria = {}
for fila in filas:
    cat = fila["categoria"]
    importe = int(fila["unidades"]) * float(fila["precio"])
    por_categoria[cat] = por_categoria.get(cat, 0) + importe

for cat, importe in sorted(por_categoria.items(), key=lambda x: -x[1]):
    print(f"{cat:15} {importe:8.2f} €")

Step 4: the best-selling product

Another dictionary, this time product → units. max() with key returns the key with the highest value.

unidades_por_producto = {}
for fila in filas:
    p = fila["producto"]
    unidades_por_producto[p] = unidades_por_producto.get(p, 0) + int(fila["unidades"])

estrella = max(unidades_por_producto, key=unidades_por_producto.get)
print(f"Más vendido: {estrella} ({unidades_por_producto[estrella]} uds)")

Where to go next

  • Use collections.Counter and defaultdict to shorten the grouping code.
  • Filter by month with fila["fecha"].startswith("2024-01").
  • Write a summary CSV with csv.writer.
  • Make the jump to pandas: df.groupby("categoria")["importe"].sum() does the same in one line.