"""Python for Excel users — lists, dicts and loops. 8 exercises with answers at the bottom.
Run:  python exercises.py      (needs orders.csv in the same folder; no extra libraries)
"""
import csv

rows = list(csv.DictReader(open("orders.csv", encoding="utf-8")))
for r in rows:
    r["Amount"] = float(r["Amount"])

# 1. How many orders are there?                              (like =COUNTA)
# 2. Total of Amount                                          (like =SUM)
# 3. Total for region "North"                                 (like =SUMIF)
# 4. A dict of total per region                               (like a pivot table)
# 5. The largest single order (whole row)                      (like =MAX + INDEX/MATCH)
# 6. List of unique customers, sorted                          (like =SORT(UNIQUE()))
# 7. Orders above 5,000 as a new list                          (like =FILTER)
# 8. Write region totals to region_totals.csv                  (like copy → paste values)

# ---------------- answers ----------------
print("1.", len(rows))
print("2.", sum(r["Amount"] for r in rows))
print("3.", sum(r["Amount"] for r in rows if r["Region"] == "North"))
totals = {}
for r in rows:
    totals[r["Region"]] = totals.get(r["Region"], 0) + r["Amount"]
print("4.", totals)
print("5.", max(rows, key=lambda r: r["Amount"]))
print("6.", sorted({r["Customer"] for r in rows}))
big = [r for r in rows if r["Amount"] > 5000]
print("7.", len(big), "orders above 5,000")
with open("region_totals.csv", "w", newline="", encoding="utf-8") as f:
    w = csv.writer(f); w.writerow(["Region", "Total"]); w.writerows(sorted(totals.items()))
print("8. region_totals.csv written")
