# Lesson 7: reading and writing files (CSV) with the standard library
import csv
from collections import defaultdict
totals = defaultdict(float)
with open("sales.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        totals[row["region"]] += int(row["qty"]) * float(row["rate"])
with open("region_totals.csv", "w", newline="", encoding="utf-8") as f:
    w = csv.writer(f)
    w.writerow(["region", "sales"])
    for region in sorted(totals):
        w.writerow([region, round(totals[region])])
        print(f"{region:<6} Rs {totals[region]:>12,.0f}")
print("Wrote region_totals.csv")
