import json from pathlib import Path DATA = Path("budget.json") def load(): return json.loads(DATA.read_text()) if DATA.exists() else [] def add(expenses, category, amount): expenses.append({"category": category, "amount": amount}) DATA.write_text(json.dumps(expenses, indent=2)) def report(expenses): totals = {} for e in expenses: totals[e["category"]] = totals.get(e["category"], 0) + e["amount"] for cat, total in sorted(totals.items(), key=lambda kv: -kv[1]): print(f"{cat:<12} {total:8.2f}") if __name__ == "__main__": expenses = load() while (cmd := input("add/report/quit: ")) != "quit": if cmd == "add": add(expenses, input("category: "), float(input("amount: "))) elif cmd == "report": report(expenses)