Sum revenue per day from a log file too big to load whole
A revenue log at path has one order per line as day,order_id,amount (for example 2026-07-15,A17,42.50). The file is far larger than RAM. Return a dict mapping each day to its total revenue, without ever loading the whole file.
Assume every line is well-formed.
def revenue_per_day(path: str) -> dict[str, float]:
# your code here
Write the implementation.
Iterate the file object line by line — Python reads it lazily, so memory stays flat. Parse each line's day and amount, adding the amount into a dict keyed by day. Never call read() or readlines(), which load the whole file at once.
- ✗Calling read() or readlines(), loading the whole file
- ✗Splitting on byte boundaries and cutting a line in half
- ✗Reaching for pandas on a file larger than memory
- →Why does iterating the file object keep memory flat?
- →How would you handle a malformed line without crashing?
Iterating an open file yields one line at a time, so peak memory is one line plus the result dict — independent of file size. Accumulate with dict.get or a defaultdict.
from collections import defaultdict
def revenue_per_day(path):
totals = defaultdict(float)
with open(path) as f:
for line in f:
day, _order_id, amount = line.rstrip("\n").split(",")
totals[day] += float(amount)
return dict(totals)
The key discipline is never materialising the whole file: for line in f reads lazily, whereas f.read() or f.readlines() would load every byte at once and blow past RAM on a file this large.