Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Build a small expense tracker by giving each Python collection the job it handles best: a list keeps transactions in sequence, dict objects hold named fields and category totals, a set tracks unique categories, and a tuple groups fixed values. For currency arithmetic, store input as decimal text and convert it to Decimal rather than using binary floats.

What is the difference between a list, tuple, set, and dictionary in Python?

The choice comes down to what you need the data to do: preserve sequence, map keys to values, enforce uniqueness, or keep a group of values fixed. This project uses the collections in those roles instead of trying to force every kind of data into one structure.

Collection Order Mutable? Distinctness Expense tracker role
list Sequence order Yes Duplicates allowed Ordered transactions
dict Insertion order is guaranteed in Python 3.7 and later Yes Keys are unique Named transaction fields and category totals
set Unordered Yes Elements are unique Unique categories and membership checks
tuple Sequence order No Duplicates allowed Fixed groups of values

The Python Software Foundation’s Python 3.14.8 tutorial describes a set as “an unordered collection with no duplicate elements.” Use a set when uniqueness or membership matters, not when display order does. Tuples are useful for fixed groupings; they can be dictionary keys only if all their contents are hashable. For named, editable fields such as an expense’s category and amount, a dictionary is usually clearer.

How do I use Python lists and dictionaries in an expense tracker?

Represent the transaction history as a list of dictionaries. The list retains the order in which records are stored, and each dictionary makes a transaction’s named fields easy to read and update.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
expenses = [
    {
        "date": "2026-10-04",
        "category": "food",
        "description": "lunch",
        "amount": "12.34",
    }
]

new_expense = {
    "date": "2026-10-04",
    "category": "transport",
    "description": "bus fare",
    "amount": "2.50",
}
expenses.append(new_expense)

for expense in expenses:
    print(expense["date"], expense["category"], expense["description"], expense["amount"])

Each record has the same four fields, and the amount is intentionally stored as text. Convert it to a numeric type only when doing arithmetic. append() adds a record to the end of the list; iterating over the list displays records in their stored sequence. Python’s data-structures tutorial also documents list operations such as remove() and pop(), as well as comprehensions for creating filtered or transformed lists.

Check required fields before using them

Dictionary subscripting, as in expense["amount"], raises KeyError if that key is missing. If absence is expected, check membership or use get() deliberately. For example, expense.get("category") returns None when the field is absent; it does not make an incomplete record valid. Validate required fields before storing or calculating from a transaction.

required = {"date", "category", "description", "amount"}
missing = required - expense.keys()
if missing:
    raise ValueError(f"Missing fields: {', '.join(sorted(missing))}")

This validation uses a set to compare field names without depending on their order. Sorting the missing names gives a stable message for display.

How do I calculate totals by category in Python?

Use a dictionary whose keys are categories and whose values are running totals. Convert each amount from its stored decimal string to Decimal before adding it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
from decimal import Decimal

totals = {}
for expense in expenses:
    category = expense["category"]
    amount = Decimal(expense["amount"])
    totals[category] = totals.get(category, Decimal("0")) + amount

for category in sorted(totals):
    print(category, totals[category])

totals.get(category, Decimal("0")) supplies zero for a category that has not appeared yet; a direct subscript of a missing key would raise KeyError. The final loop sorts dictionary keys to produce alphabetical output. The dictionary itself preserves insertion order in Python 3.7 and later, but alphabetical order is a separate display choice.

How should I handle money in Python?

Use Decimal created from strings for exact decimal currency arithmetic. Binary floating-point cannot exactly represent many decimal values; for example, decimal values such as 1.1 and 2.2 do not have exact binary floating-point representations. Python’s Decimal documentation identifies Decimal as preferred for accounting applications that need strict equality invariants.

Do not first parse the amount as a float and then wrap that result in Decimal: the binary approximation would already have entered the calculation. Keeping input as text, as in "12.34", lets Decimal(expense["amount"]) construct the intended decimal value.

Make the rounding rule explicit when displaying fixed-place currency. For example, this rounds to two decimal places using Decimal’s configured rounding context:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
from decimal import Decimal

shown_total = totals["food"].quantize(Decimal("0.01"))
print(shown_total)

The example specifies two places, but does not choose a universal business rounding policy. A real tracker should choose and document its rule where amounts are accepted or displayed, especially if its currency or accounting requirements differ.

When should I use a set or tuple in the tracker?

Use a set for unique categories or membership

A set removes duplicates and supports membership checks. Derive distinct category names from the transaction list, then sort them if the user-facing output needs a predictable alphabetical order.

categories = {expense["category"] for expense in expenses}
for category in sorted(categories):
    print(category)

The set is not the place to keep transaction order. Convert or sort its values for display instead of relying on an iteration order.

Use a tuple only for a fixed grouping

A tuple can represent a fixed positional grouping, such as coordinates or a pair of values used as a key when all members are hashable. For an expense record with named fields that may need validation or editing, a dictionary communicates the meaning of each value more clearly. A tuple’s immutability is useful when the grouping should not change.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How do I save expense data to a CSV or JSON file in Python?

Choose a format according to the shape and intended use of the data. CSV fits rows and columns and is convenient for spreadsheet-compatible transaction records. JSON is suited to structured data, including nested values. Neither file format by itself provides privacy, encryption, backup, or safe simultaneous multi-user access.

Save tabular transactions as CSV

Python’s CSV module includes DictWriter for writing dictionaries as rows and DictReader for reading rows back as dictionaries. Keep the amount as text so it can later be converted directly to Decimal.

import csv

fields = ["date", "category", "description", "amount"]
with open("expenses.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.DictWriter(file, fieldnames=fields)
    writer.writeheader()
    writer.writerows(expenses)

with open("expenses.csv", newline="", encoding="utf-8") as file:
    loaded_expenses = list(csv.DictReader(file))

CSV rows are textual data when read, so the amount remains suitable for Decimal(loaded_expense["amount"]) rather than being interpreted as a float.

Save structured data as JSON

Python’s standard-library JSON module serializes and parses JSON. A list of transaction dictionaries maps naturally to JSON, and the module preserves input and output order by default when the underlying containers are ordered.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
import json

with open("expenses.json", "w", encoding="utf-8") as file:
    json.dump(expenses, file, indent=2)

with open("expenses.json", encoding="utf-8") as file:
    loaded_expenses = json.load(file)

JSON preserves the amount strings in this example. Convert them to Decimal when calculating totals, just as with CSV input. CSV remains the more direct fit if users primarily need to inspect or edit rows in spreadsheet software; JSON is useful when the saved structure grows beyond a simple table.

When are other Python collections useful?

Keep the core tracker simple until its behavior calls for another collection. A list is fine for appending and iterating through transactions. A deque becomes relevant when a feature repeatedly adds or removes items at both ends, such as queue behavior. Python documents fast operations at both ends for collections.deque; removing or inserting at the front of a list requires moving the remaining elements and takes O(n) work.

For ordinary tracker summaries, category dictionaries, sorted output, and simple list comprehensions are enough. Introducing a specialized structure without a corresponding operation makes the data flow harder to understand rather than improving the design.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.