Python Lists vs. Dicts and Streaming Messy Files
Medium · Data Manipulation (SQL/Python) · Data Scientist · Onsite
Problem Statement
Data-engineering pipelines regularly choose between positional and hashed Python containers in memory while streaming multi-gigabyte text exports that will not fit in RAM at once. Along with understanding how CPython 3 list and dict compare on operation complexity, memory overhead, and ordering — and when JSON Lines beats CSV or how to size chunked DataFrame reads on a 16 GB machine — implement a zero-dependency Python streaming aggregator that totals a numeric field across arbitrarily large, messy JSON Lines and CSV byte streams in O(1) working memory.
Implement the three functions declared in starter.py (sharing MISSING_TEXT = {"", "na", "n/a", "nan", "null", "none"}):
-
parse_value(raw) -> Optional[float]- Converts a single raw cell or JSON primitive into a finite
float, or returnsNoneifrawrepresents a missing entry. - Missing entries:
None, floating-pointNaN, or a string whose.strip().lower()matchesMISSING_TEXT. - Invalid entries (
ValueError): Any non-numeric text (such as"oops"), booleans (TrueorFalse), containers (list,dict), infinities ("inf",float("inf")), or numbers exceeding IEEE-754float64range ("1e400",10**400).
- Converts a single raw cell or JSON primitive into a finite
-
sum_jsonl(byte_lines: Iterable[bytes], field: str = "value") -> Dict- Iterates lazily over raw byte lines of a JSON Lines stream and returns
{"total": float, "used": int, "missing": int, "bad": int}. - Decodes each line from UTF-8, stripping a leading UTF-8 byte-order mark (
\xef\xbb\xbf) on the first line only and replacing invalid byte sequences withU+FFFD(errors="replace"). - Ignores empty or whitespace-only lines completely.
- Increments
"missing"whenfieldis omitted from the JSON object orparse_valuereturnsNone. - Increments
"bad"whenjson.loadsfails (syntax errors, oversized integer literals, or excessive nesting depth), when the decoded JSON value is not adict, or whenparse_valueraisesValueError. - Raises
OverflowErrorif the accumulated"total"overflowsfloat64.
- Iterates lazily over raw byte lines of a JSON Lines stream and returns
-
sum_csv(byte_lines: Iterable[bytes], column: str = "value") -> Dict- Streams a headered CSV byte-line iterable via
csv.DictReaderusing the same UTF-8 decoding, blank-line skipping, return dictionary structure, and running-sumOverflowErrorcheck assum_jsonl. - Raises
ValueErrorif the file has no valid header row orcolumnis absent from the header. - Increments
"bad"whenevercsvraisescsv.Erroron a record, when a row has fewer or more fields than the header (even ifcolumnitself was already populated earlier in the row), or whenparse_valuerejects the cell incolumn.
- Streams a headered CSV byte-line iterable via
Examples
Example 1
lines = [
b'\xef\xbb\xbf{"event": "a", "value": 15.5}\n',
b" \n",
b'{"event": "b", "value": " -3.25 "}\n',
b'{"event": "c"}\n',
b'{"event": "d", "value": "n/a"}\n',
b'{"event": "e", "value": false}\n',
b'{"event": "f", "value": 1e400}\n',
b"broken json\n",
b'{"event": "g", "note": "r\xe9sum\xe9", "value": 4.75}',
]
sum_jsonl(lines, field="value")
Output:
{"total": 17.0, "used": 3, "missing": 2, "bad": 3}
Walk-through: Line 1 strips the UTF-8 BOM and adds 15.5; line 2 is whitespace-only and skipped; line 3 parses " -3.25 " (15.5 - 3.25 = 12.25); lines 4 and 5 record 2 missing values (absent key and "n/a"); lines 6–8 record 3 bad lines (false boolean, 1e400 float64 overflow, and invalid JSON); and line 9 replaces the non-UTF-8 \xe9 bytes inside "note" while cleanly adding 4.75 (12.25 + 4.75 = 17.0).
Example 2
csv_stream = [
b"\xef\xbb\xbftx_id,amount,memo\r\n",
b'101,24.0,"Parts, labor"\r\n',
b"102, NULL ,ok\r\n",
b"103,8.5\r\n",
b"104,oops,ok\r\n",
b"105,-4.5,caf\xe9\r\n",
b"106,,ok\r\n",
b"107,3.0,ok,extra\r\n",
]
sum_csv(csv_stream, column="amount")
Output:
{"total": 19.5, "used": 2, "missing": 2, "bad": 3}
Walk-through: After stripping the BOM from the header tx_id,amount,memo, rows 101 (24.0) and 105 (-4.5) contribute total = 19.5 (used = 2). Rows 102 (" NULL ") and 106 ("") increment missing to 2. Row 103 has only two columns instead of three, row 104 has non-numeric "oops", and row 107 has four columns, incrementing bad to 3.
Constraints
- True streaming (
O(1)extra row memory):byte_linesmay be a one-pass generator yielding millions of lines; never call.read()or materialize all rows in a list. - Strict numeric & boolean rules:
parse_value(7)must return afloat(7.0), whileparse_value(True)andparse_value(False)must raiseValueError. Individual overflowing cells (1e400,10**400) count as"bad", whereas valid cells whose running sum overflowsfloat64(1e308 + 1e308) must raiseOverflowError. - Empty inputs: An empty or blank-only JSON Lines stream returns
{"total": 0.0, "used": 0, "missing": 0, "bad": 0}. An empty CSV stream raisesValueError(no header), while a header-only CSV with the target column returns{"total": 0.0, "used": 0, "missing": 0, "bad": 0}.
Step-by-step walkthrough
Python list vs dict: operations, Big-O, memory, and ordering
In CPython 3, a
listis a dynamic array (a single contiguous block of memory storing8-byte pointers to Python objects, indexed by integer position0 .. n-1). Adictis an open-addressed hash table (a sparse index array pointing into a compact table of[hash, key_ptr, value_ptr]entries, indexed byhash(key)):list (dynamic array of 8-byte pointers, over-allocated for fast append): index: [ 0 | 1 | 2 | unused | unused ] value: [ 12.5| 8.0| 4.0| -- | -- ] dict (compact insertion-ordered entries + sparse hash index table): indices: [ -1 | 1 | -1 | 0 | -1 | 2 ] (at most 2/3 full) entries: slot 0: [ hash("red"), "red", 2 ] slot 1: [ hash("blue"), "blue", 1 ] slot 2: [ hash("green"), "green", 5 ]Every time and memory trade-off follows directly from those two layouts:
Operation list(average / worst)dict(average / worst)Append / add new lst.append(x): O(1) amortized / O(n) resized[k] = v(new key): O(1) average / O(n) collision or resizeInsert at position ilst.insert(i, x): O(n - i) average and worstNot applicable (keyed, not positional) Lookup lst[i]: O(1);x in lst/lst.index(x): O(n)d[k],d.get(k),k in d: O(1) average / O(n) worstUpdate existing lst[i] = x: O(1) average and worstd[k] = v(existing key): O(1) average / O(n) worstDelete lst.pop(): O(1) amortized;lst.pop(i)/del lst[i]: O(n - i);lst.remove(x): O(n)del d[k],d.pop(k): O(1) average / O(n) worstWhy the worst cases and memory differences happen:
- Amortized growth vs middle shifts (
list): When a list fills its spare capacity, CPython allocates a new buffer roughly12.5%larger and copies allnpointers (O(n)once), spreading out to O(1) amortized cost per append. Inserting or popping at index0shifts allnpointers every single call (O(n)), which is why queues usecollections.dequeinstead. - Hash collisions and table resizes (
dict): Looking upd[k]jumps straight tohash(k) % table_sizein O(1) on average. If adversarial or buggy keys all share the same hash (hash collision), CPython must probeO(n)slots per lookup (mitigated for strings by per-process hash randomization viaPYTHONHASHSEED). Once the sparse index table reaches2/3full, the next new key triggers anO(n)rebuild. - Memory footprint (64-bit CPython 3): A
1,000,000-elementlistcontainer takes about8.0-8.5 MB(8bytes per pointer + small header + ~12.5%spare slots), whereas a1,000,000-entrydictcontainer takes roughly31-42 MB(3.5-5xlarger) because each entry storeshash + key + value(24bytes, or16bytes for compact all-strkeys in Python 3.11+) plus the<= 2/3-full index array. Crucially,del d[k]writes a dummy tombstone and never shrinks the allocated table until you copy it (d = dict(d)). - Ordering guarantees:
listpreserves positional order. Since Python 3.7,dictpreserves insertion order by language specification (in CPython 3.6 it was an implementation side effect): overwriting an existing keyd[k] = new_vkeeps its original position, whiledel d[k]followed byd[k] = new_vmoveskto the end.
# Storing and retrieving in a list (positional): prices = [] prices.append(12.5) # O(1) amortized append at end prices.append(8.0) first_price = prices[0] # O(1) positional lookup -> 12.5 # Storing and updating in a dict (keyed): counts = {} for word in ["red", "blue", "red"]: counts[word] = counts.get(word, 0) + 1 # O(1) average insert/update counts.update({"green": 5}) # batch key-value update print(first_price, counts["red"], counts.get("yellow", 0)) # 12.5 2 0- Amortized growth vs middle shifts (
JSON vs CSV: trade-offs and when to choose JSON
Compare the same two records in JSON Lines (one self-describing JSON value per line) versus CSV (a flat comma-separated text table):
JSON Lines (nested, typed, evolving keys): {"id": 1, "value": 42.5, "tags": ["urgent", "plumbing"]} {"id": 2, "value": null, "promo_code": "SPRING10"} CSV (flat text grid, fixed columns): id,value,tags 1,42.5,"urgent|plumbing" 2,,- Structure & nesting: JSON (RFC 8259) natively represents nested objects, variable-length lists, numbers, booleans, and
null(standard JSON forbidsNaN,Infinity, and comments). CSV (RFC 4180) is strictly a flat 2D text grid where commas, quotes, and newlines inside cells require double-quoting (""escapes a quote). - Schema evolution & types: Choose JSON / JSON Lines when records are nested, when upstream services add optional fields over time (an absent key,
null,"",42, and"42"are all distinct without breaking older consumers), or when exchanging data with web APIs and event logs. Adding a column in the middle of a CSV breaks positional readers, and CSV cannot distinguishNULLfrom an empty string""without out-of-band conventions. - Size, compression, and analytics: Choose CSV for flat, fixed-schema tables exchanged with spreadsheets or
COPYbulk-loaders — writing column names once makes uncompressed CSV roughly2.5-3xsmaller than JSON Lines. Undergziporzstd, dictionary compression collapses repeated JSON keys so compressed JSON Lines shrinks to within ~1.15xof compressed CSV (note that a single.gzstream cannot be split across parallel workers without block compression). At scale for analytics, columnar Parquet beats both with strict types, per-column compression, and reading only the'value'column from disk.
- Structure & nesting: JSON (RFC 8259) natively represents nested objects, variable-length lists, numbers, booleans, and
Parse one raw cell safely with parse_value
To stream a messy 10 GB file without crashing or silently corrupting the sum, both our JSON Lines and CSV readers share one cell-level function
parse_value(raw):- Missing markers (
Nonereturned): PythonNone, floating-pointNaN, or any case/whitespace variation of"","na","n/a","nan","null","none". - Invalid or overflowing cells (
ValueErrorraised):- Check
isinstance(raw, bool)before(int, float)becauseboolsubclassesintin Python — otherwiseTruesilently adds1.0to your sum! float(10**400)raisesOverflowError(notValueError), so catch and convert it toValueError.float("1e400")and Python'sjson.loads("1e400")do not raise; they silently return+inf! Checkingmath.isinf(number)catches"1e400"and"inf"before a single bad row turns the entire sum intoinf.
- Check
from typing import Optional import math MISSING_TEXT = {"", "na", "n/a", "nan", "null", "none"} def parse_value(raw) -> Optional[float]: # Phase 1: handle explicit null/None and reject booleans before checking numeric types, # because bool is a subclass of int in Python (isinstance(True, int) is True). if raw is None: return None if isinstance(raw, bool): raise ValueError(f"not a number: {raw!r}") # Phase 2: convert strings or numeric primitives into a Python float64. if isinstance(raw, str): cleaned_text = raw.strip() if cleaned_text.lower() in MISSING_TEXT: return None number = float(cleaned_text) elif isinstance(raw, (int, float)): try: number = float(raw) except OverflowError as exc: # Huge Python ints like 10**400 raise OverflowError in float(); normalize to ValueError. raise ValueError(f"too large for a float64: {raw!r}") from exc else: raise ValueError(f"not a number: {raw!r}") # Phase 3: float("nan") / JSON NaN counts as missing; float("1e400") silently produces inf, # so we must check math.isinf explicitly to reject float64 overflows as bad cells. if math.isnan(number): return None if math.isinf(number): raise ValueError(f"not a finite float64: {raw!r}") return number- Missing markers (
Track row counts, cap warnings, and decode UTF-8 safely
Every non-blank record lands in exactly one bucket —
used,missing, orbad— so a production job can assert data completeness and alert if thebadfraction spikes, whileMAX_LOGGED = 10keeps a broken 100-million-row file from filling the disk with warning logs.For bad encodings, opening a file in default text mode (
open(path, "r")) crashes mid-run withUnicodeDecodeErroron the first stray Latin-1 byte (\xe9or\xff). Instead, iterate binary lines and decode each line ourselves:- Decode line 1 with
"utf-8-sig"to strip an optional Byte-Order Mark (BOM) (\xef\xbb\xbfadded by Excel/Windows exports, which would otherwise turn header"value"into"\ufeffvalue"or breakjson.loads), then switch to"utf-8"for line2+. - Pass
errors="replace"so undecodable bytes become the Unicode replacement characterU+FFFD(`). If the stray byte was inside an unusednamecolumn, the numericvaluestill sums cleanly; if it hitvalue,parse_valuerejects it asbad`. - Finally,
finish()checksmath.isfinite(stats["total"])so two valid floats whose running sum overflows float64 (1e308 + 1e308 -> inf) raiseOverflowError.
from typing import Dict, Iterable, Iterator import logging import math LOG = logging.getLogger(__name__) MAX_LOGGED = 10 def new_stats() -> Dict: # stats shape: {"total": float sum, "used": valid count, "missing": null/NA count, "bad": malformed count} return {"total": 0.0, "used": 0, "missing": 0, "bad": 0} def mark_bad(stats: Dict, where: str, reason: str) -> None: stats["bad"] += 1 # Rate-limit warnings while still keeping the exact bad-row count across the entire stream. if stats["bad"] <= MAX_LOGGED: LOG.warning("skipping %s: %s", where, reason) def add_value(stats: Dict, raw, where: str) -> None: try: value = parse_value(raw) except ValueError as exc: mark_bad(stats, where, str(exc)) return if value is None: stats["missing"] += 1 else: stats["total"] += value stats["used"] += 1 def finish(stats: Dict) -> Dict: # Two finite float64s like 1e308 + 1e308 overflow to +inf without raising; catch that here. if not math.isfinite(stats["total"]): raise OverflowError("the running sum does not fit in a float64") return stats def decode_lines(byte_lines: Iterable[bytes]) -> Iterator[str]: encoding = "utf-8-sig" for raw_bytes in byte_lines: yield raw_bytes.decode(encoding, errors="replace") encoding = "utf-8"- Decode line 1 with
Stream JSON Lines line by line with sum_jsonl
Iterating directly over
open("data.jsonl", "rb")yields one line at a time, holding onlyO(longest line)in RAM regardless of whether the file is 10 MB or 10 TB. Aroundjson.loads(line), catch(ValueError, RecursionError)rather than onlyjson.JSONDecodeError: in Python 3.11+, a 5,000-digit integer triggerssys.set_int_max_str_digitsand raises a plainValueError, while 100,000 nested[brackets raiseRecursionError. Also verifyisinstance(record, dict)so valid non-object JSON lines like[1, 2]are counted asbad, while an absent key (record.get(field)returningNone) counts asmissingfor backward-compatible schema evolution:Input line Bucket Running total \xef\xbb\xbf{"event": "a", "value": 15.5} used 15.50 (BOM stripped) (whitespace-only line) skipped 15.50 {"event": "b", "value": " -3.25 "} used 12.25 (numeric string) {"event": "c"} / {"event": "d", "value": "n/a"} missing 12.25 (absent or missing marker) {"value": false} / {"value": 1e400} bad 12.25 (boolean or float overflow) broken json bad 12.25 (malformed JSON) {"event": "g", "note": "r\xe9sum\xe9", "value": 4.75} used 17.00 (bad byte outside value)from typing import Dict, Iterable import json def sum_jsonl(byte_lines: Iterable[bytes], field: str = "value") -> Dict: stats = new_stats() line_no = 0 for line in decode_lines(byte_lines): line_no += 1 if not line.strip(): continue where = f"line {line_no}" # Catch plain ValueError (raised by integers > 4,300 digits) and RecursionError # (raised by deeply nested brackets) in addition to JSONDecodeError (a ValueError subclass). try: record = json.loads(line) except (ValueError, RecursionError) as exc: mark_bad(stats, where, f"invalid JSON ({exc})") continue if not isinstance(record, dict): mark_bad(stats, where, "not a JSON object") continue add_value(stats, record.get(field), where) return finish(stats)Stream CSV with csv.DictReader and sum_csv (the non-pandas alternative)
csv.DictReaderconsumes ourdecode_linesgenerator one record at a time using only the Python standard library — makingsum_csvour safe, zero-dependency non-pandas streaming alternative. Becausedecode_linespreserves\r\nand\nline endings, quoted multi-line cells like"two\r\nlines"stay intact as one record.Notice how
csv.DictReadersignals ragged rows in the dictionary it yields for headertx_id,amount,memo:CSV line DictReader output dict Classification 101,24.0,ok -> {"tx_id": "101", "amount": "24.0", "memo": "ok"} -> valid width -> parse_value("24.0") 106,,ok -> {"tx_id": "106", "amount": "", "memo": "ok"} -> valid width -> "" is missing 103,8.5 -> {"tx_id": "103", "amount": "8.5", "memo": None} -> None in row.values() -> bad (too few) 107,3.0,ok,ex -> {"tx_id": "107", "amount": "3.0", "memo": "ok", None: ["ex"]} -> None in row -> bad (too many)Stepping manually with
next(reader)insidewhile Truealso lets us catchcsv.Error(such as a single corrupt field exceedingcsv.field_size_limit(),131,072chars) and continue with the next row. One CSV caveat to mention in interviews: an unclosed double quote swallows subsequent lines until the next quote or the131,072-char limit, so always compareused + missing + badagainst expected row counts in production.from typing import Dict, Iterable import csv def sum_csv(byte_lines: Iterable[bytes], column: str = "value") -> Dict: reader = csv.DictReader(decode_lines(byte_lines)) try: fieldnames = reader.fieldnames except csv.Error as exc: raise ValueError(f"invalid CSV header: {exc}") from exc if fieldnames is None or column not in fieldnames: raise ValueError(f"the header has no {column!r} column") stats = new_stats() while True: try: row = next(reader) except StopIteration: break except csv.Error as exc: mark_bad(stats, f"the row after line {reader.line_num}", str(exc)) continue where = f"line {reader.line_num}" if None in row: mark_bad(stats, where, "too many fields") elif None in row.values(): mark_bad(stats, where, "too few fields") else: add_value(stats, row[column], where) return finish(stats)Stream with pandas chunksize and size chunks for 10 GB on 16 GB RAM
With
pandas, passingchunksizetopd.read_csvreturns a lazy iterator of DataFrames so only one chunk resides in RAM at a time. Read'value'asstrfirst so a single"abc"cell cannot crash C-engine float parsing for the entire chunk, coerce withpd.to_numeric(..., errors="coerce"), and guard against both cell-levelinf("1e400") and running-sum overflow:import math import numpy as np import pandas as pd MISSING_MARKERS = {"", "na", "n/a", "nan", "null", "none"} total = 0.0 used = missing = bad = 0 with pd.read_csv( "data.csv", dtype={"value": str}, # keep raw strings so one bad cell cannot abort the chunk keep_default_na=False, # classify missing markers explicitly after strip() chunksize=1_000_000, # ~1M rows per batch; sized from the RAM budget below encoding="utf-8-sig", # strip a leading UTF-8 BOM encoding_errors="replace", # replace bad bytes with U+FFFD instead of crashing on_bad_lines="warn", # skip and warn on rows with extra delimiter fields ) as reader: for chunk in reader: cleaned = chunk["value"].str.strip() numeric = pd.to_numeric(cleaned, errors="coerce") # "abc" -> NaN, "1e400" -> inf is_missing = cleaned.str.lower().isin(MISSING_MARKERS) is_valid = ~is_missing & np.isfinite(numeric) total += float(numeric[is_valid].sum()) if not math.isfinite(total): raise OverflowError("running sum overflowed float64") used += int(is_valid.sum()) missing += int(is_missing.sum()) bad += int((~is_missing & ~is_valid).sum())Note also why we avoid
int64sums on untrusted integers in NumPy/pandas: unlike Pythonint,int64overflows wrap around silently (np.array([2**62, 2**62]).sum()is negative!).Sizing batches for a 10 GB CSV within a 16 GB memory ceiling:
16 GB total RAM - 4 GB OS + background processes + file-cache headroom - 9 GB safety margin + temporary vectorized arrays (cleaned, numeric, boolean masks ~ 2-3x chunk) = ~1 GB target in-memory DataFrame footprint per chunk Step 1 (measure, don't guess): sample = pd.read_csv("data.csv", nrows=100_000, dtype={"value": str}, keep_default_na=False) bytes_per_row = sample.memory_usage(deep=True).sum() / len(sample) Step 2 (convert disk size to in-memory size): Suppose disk rows average ~100 bytes (100M rows in 10 GB). In-memory strings expand ~2x (PyArrow strings) to ~6x (Python object strings) -> ~200-600 B/row. At 600 B/row, a 1 GB chunk budget holds ~1.67M rows -> pick chunksize = 1_000_000 (~600 MB/chunk). (If schema integrity is already trusted and usecols=["value"] is safe, 1M rows takes < 60 MB.)Avoid tiny chunks (
< 50,000rows), which spend more time in Python loop/DataFrame construction overhead than in C-level parsing.Complete solution
Putting
parse_value, the shared counting and UTF-8 line-decoding helpers,sum_jsonl, andsum_csvtogether intosolution.py:from typing import Dict, Iterable, Iterator, Optional import csv import json import logging import math LOG = logging.getLogger(__name__) # Normalized cell texts that mean "no value" (checked after strip() and lower()). MISSING_TEXT = {"", "na", "n/a", "nan", "null", "none"} # Cap warning logs so a corrupt 10 GB file cannot flood disk with millions of log lines. MAX_LOGGED = 10 def parse_value(raw) -> Optional[float]: """Turn one raw cell into a finite float, or None when the cell means "missing". Missing: None, NaN, and the texts in MISSING_TEXT (any case, surrounding spaces ignored). Raises ValueError for everything else that is not a finite number: text such as "abc", booleans, lists or dicts, and numbers that do not fit in a float64 ("1e400", "inf", 10**400). """ # Phase 1: handle explicit null/None and reject booleans before checking numeric types, # because bool is a subclass of int in Python (isinstance(True, int) is True). if raw is None: return None if isinstance(raw, bool): raise ValueError(f"not a number: {raw!r}") # Phase 2: convert strings or numeric primitives into a Python float64. if isinstance(raw, str): cleaned_text = raw.strip() if cleaned_text.lower() in MISSING_TEXT: return None number = float(cleaned_text) elif isinstance(raw, (int, float)): try: number = float(raw) except OverflowError as exc: # Huge Python ints like 10**400 raise OverflowError in float(); normalize to ValueError. raise ValueError(f"too large for a float64: {raw!r}") from exc else: raise ValueError(f"not a number: {raw!r}") # Phase 3: float("nan") / JSON NaN counts as missing; float("1e400") silently produces inf, # so we must check math.isinf explicitly to reject float64 overflows as bad cells. if math.isnan(number): return None if math.isinf(number): raise ValueError(f"not a finite float64: {raw!r}") return number def new_stats() -> Dict: # stats shape: {"total": float sum, "used": valid count, "missing": null/NA count, "bad": malformed count} return {"total": 0.0, "used": 0, "missing": 0, "bad": 0} def mark_bad(stats: Dict, where: str, reason: str) -> None: stats["bad"] += 1 # Rate-limit warnings while still keeping the exact bad-row count across the entire stream. if stats["bad"] <= MAX_LOGGED: LOG.warning("skipping %s: %s", where, reason) def add_value(stats: Dict, raw, where: str) -> None: try: value = parse_value(raw) except ValueError as exc: mark_bad(stats, where, str(exc)) return if value is None: stats["missing"] += 1 else: stats["total"] += value stats["used"] += 1 def finish(stats: Dict) -> Dict: # Two finite float64s like 1e308 + 1e308 overflow to +inf without raising; catch that here. if not math.isfinite(stats["total"]): raise OverflowError("the running sum does not fit in a float64") return stats def decode_lines(byte_lines: Iterable[bytes]) -> Iterator[str]: """Yield each byte line as UTF-8 text, stripping a leading BOM and replacing invalid bytes.""" # Use utf-8-sig only on the very first line so a UTF-8 byte-order mark (\xef\xbb\xbf) is dropped # from line 1 without stripping legitimate \ufeff characters on later lines. encoding = "utf-8-sig" for raw_bytes in byte_lines: yield raw_bytes.decode(encoding, errors="replace") encoding = "utf-8" def sum_jsonl(byte_lines: Iterable[bytes], field: str = "value") -> Dict: """Stream a JSON Lines file (e.g. open(path, "rb")) and sum `field` over its records. Returns {"total": float, "used": int, "missing": int, "bad": int}. Blank lines are skipped. missing: the field is absent, null, NaN or a missing-value text. bad: json.loads rejects the line, it is not a JSON object, or the field is not a finite number. """ stats = new_stats() line_no = 0 for line in decode_lines(byte_lines): line_no += 1 if not line.strip(): continue where = f"line {line_no}" # Catch plain ValueError (raised by integers > 4,300 digits) and RecursionError # (raised by deeply nested brackets) in addition to JSONDecodeError (a ValueError subclass). try: record = json.loads(line) except (ValueError, RecursionError) as exc: mark_bad(stats, where, f"invalid JSON ({exc})") continue # A valid JSON line like "[1, 2]" or "42" is not a key-value record object. if not isinstance(record, dict): mark_bad(stats, where, "not a JSON object") continue add_value(stats, record.get(field), where) return finish(stats) def sum_csv(byte_lines: Iterable[bytes], column: str = "value") -> Dict: """Stream a CSV file with a header row (e.g. open(path, "rb")) with csv.DictReader and sum `column`. Same result shape as sum_jsonl. bad: a row with too few or too many fields, a row the csv module cannot parse (csv.Error), or a value that is not a finite number. Raises ValueError if the header has no such column (an empty file has no header). """ reader = csv.DictReader(decode_lines(byte_lines)) try: fieldnames = reader.fieldnames except csv.Error as exc: raise ValueError(f"invalid CSV header: {exc}") from exc if fieldnames is None or column not in fieldnames: raise ValueError(f"the header has no {column!r} column") stats = new_stats() while True: # Step manually with next() so a csv.Error on one broken row (e.g. > 131,072 chars) # can be caught and counted without aborting the loop over the remaining rows. try: row = next(reader) except StopIteration: break except csv.Error as exc: mark_bad(stats, f"the row after line {reader.line_num}", str(exc)) continue where = f"line {reader.line_num}" # DictReader stores extra columns in a list under key None, and fills missing trailing # columns with value None (catching short rows even when `column` appeared earlier). if None in row: mark_bad(stats, where, "too many fields") elif None in row.values(): mark_bad(stats, where, "too few fields") else: add_value(stats, row[column], where) return finish(stats)✅ Submit now — all tests should pass.
Intuition & how it works
Think of Python's list vs dict like a row of numbered lockers vs a coat-check desk with name tags: a list stores object pointers side-by-side so jumping to locker #5 or adding to the end is instant, while a dict computes a hash (a numeric fingerprint of the key) to jump straight to a named slot at the cost of roughly 3.5-5x more container memory. Likewise, processing a 10 GB file on a 16 GB machine works like inspecting boxes on a conveyor belt (streaming) rather than Forklifting the entire warehouse onto your desk at once: you decode one line (or fixed-size chunk), validate one cell, update four tiny counters (total, used, missing, bad), and immediately let Python free that line's memory.
The naive approach — calling json.load(f), list(csv.DictReader(f)), or pd.read_csv("data.csv") without chunksize — expands a 10 GB text file into 25-60 GB of Python/DataFrame objects and crashes with an out-of-memory error. Even when streaming, naive open(path, "r") aborts hours into a job on a single stray non-UTF-8 byte, and naive float(x) turns "1e400" into +inf or True into 1.0, silently poisoning the entire sum.
Trace 5 lines flowing through sum_jsonl to see how each record is classified in O(1) working memory:
\xef\xbb\xbf{"event": "a", "value": 15.5}->"utf-8-sig"strips the leading Byte-Order Mark (BOM) (an invisible 3-byte header added by some editors),parse_value(15.5)returns15.5->total = 15.5, used = 1.{"event": "d", "value": " n/a "}->strip().lower()matchesMISSING_TEXT->parse_valuereturnsNone->missing = 1.{"event": "e", "value": false}-> rejected becauseboolsubclassesintin Python ->bad = 1(logged with line number).{"event": "f", "value": 1e400}->floatparses toinf, caught bymath.isinf->bad = 2(totalstays15.5, uncorrupted).{"event": "b", "value": " -3.25 "}->parse_value(" -3.25 ")returns-3.25->finish()verifiestotal = 12.25is finite and returns{"total": 12.25, "used": 2, "missing": 1, "bad": 2}.
Complexity
- Time —
O(B)acrossBinput bytes: Bothsum_jsonlandsum_csvdecode each byte once indecode_lines, parse each line once withjson.loadsorcsv.DictReader, and perform constant-time (O(1)) hash-set and float checks per record. Forlistvsdictoperations,list.appendis amortized O(1) (an occasionalO(n)pointer copy when capacity fills averages out to constant time per append) andlist.insert(i, x)/pop(i)is O(n - i) from shifting trailing pointers, whereasdictlookup/insert/update/delete is O(1) average and O(n) worst case if keys suffer hash collisions (multiple keys landing on the same hash slot) or trigger a table resize. - Space —
O(L)for streaming (O(chunksize * row_bytes)for chunked pandas): Our pure-Python readers hold only one decoded line or multi-line quoted CSV record of maximum lengthLbytes plus a 4-keystatsdictionary (O(1)), so memory never grows with row count. Chunkedpandas.read_csvallocates one DataFrame chunk at a time (~600 MBatchunksize=1_000_000for600-byte in-memory rows, comfortably inside16 GBRAM).
Edge cases
- Leading UTF-8 BOM (
\xef\xbb\xbf): Stripped on line1only via"utf-8-sig"so CSV headers are"value"(not"\ufeffvalue") and line1of JSONL parses cleanly. - Windows
\r\nand multi-line CSV quotes: Keeping raw line endings when feedingcsv.DictReaderallows"two\r\nlines"inside quotes to be assembled as a single CSV record without leaving stray\rcharacters on numbers. - Ragged CSV rows regardless of column order: With header
id,value,name, a short row2,7already populatedvalue="7", yetNone in row.values()still catches the missingnamecolumn and marks the rowbad. Extra fields land under keyNone(None in row). - Malformed/oversized CSV headers or rows: Stepping
next(reader)insidetry ... except csv.Errorcatches rows exceedingcsv.field_size_limit()(131,072characters), and wrappingreader.fieldnamesconverts broken headers intoValueError. - Hostile JSON literals: Python's
json.loadsaccepts non-standardNaN(treated asmissing) andInfinity(rejected asbad), raises plainValueErroron integers past4,300digits, and raisesRecursionErroron deep[nesting — all caught safely without stopping the stream. - Booleans and running-sum overflow:
True/Falseare rejected beforeintchecks; individual overflows (1e400,10**400) count asbad, while a running total overflowing float64 (1e308 + 1e308) raisesOverflowError. - Corrupt encodings and unclosed CSV quotes:
errors="replace"turns bad bytes intoU+FFFDso bad text in other columns never drops a valid numeric value. An unclosed CSV quote consumes lines until the next quote or the131,072-char limit; comparingused + missing + badagainst physical line count detects swallowed rows.
Common mistakes
- Calling
f.read(),f.readlines(),json.load(f), orlist(csv.DictReader(f))on multi-gigabyte files, pulling the entire file into RAM at once. - Opening dirty exports in default strict UTF-8 text mode, where one stray
\xffbyte throwsUnicodeDecodeErrorhalfway through a 10 GB job. - Catching only
json.JSONDecodeErroraroundjson.loads(missing plainValueErroron huge integers andRecursionErroron deep nesting), or wrapping the entire file loop in onetry/exceptinstead of per-row error handling. - Forgetting
isinstance(raw, bool)beforeisinstance(raw, int)or forgettingmath.isinf(float(x)), allowingTrue(1.0) or"1e400"(inf) into the total. - Summing untrusted large integer columns as NumPy/pandas
int64, which silently wraps around to negative numbers on overflow instead of raising an error. - Passing
dtype={"value": float}directly topd.read_csvon messy data (one"abc"aborts the whole chunk) instead of reading strings and callingpd.to_numeric(..., errors="coerce"). - Expecting
del d[k]to release a Pythondict's hash-table memory, or usingx in my_list(O(n)) repeatedly inside a loop instead of aset/dict(O(1)average).
Alternative approaches
- High-precision floating-point summation (
math.fsum/ Kahan summation): Standardtotal += valuecan accumulate rounding drift across10^8rows when huge and tiny numbers mix. Kahan summation (tracking a small running compensation term for lost low-order bits) or Python'smath.fsumpreserves full precision inO(1)extra memory. - Dead-letter queue + bad-row budget: Write malformed raw lines and line numbers to a separate
bad_rows.jsonlside file for replay, and fail the pipeline at the end ifbad / (used + missing + bad)exceeds a threshold such as0.1%. - Convert once to Parquet with DuckDB or PyArrow: Streaming CSV/JSONL into typed, zstd-compressed Parquet lets every downstream query scan only the
valuecolumn at gigabytes per second without reparsing text.
Follow-up questions
- How would you parallelize summing a multi-gigabyte file across 8 CPU cores? For uncompressed JSON Lines (or CSV guaranteed to have no embedded newlines inside quotes), divide the file size into
8byte ranges[start, end), have each worker seek tostartand advance past the first\n(except worker0, which reads the header first), and sum its slice independently before adding the8{total, used, missing, bad}dicts together. If the CSV may contain quoted multi-line fields or single-stream.gzcompression, arbitrary byte seeking is unsafe because a worker could land inside a quoted string or compressed stream; use one fast reader thread feeding parser workers, or store block-splittable Parquet/bgzip files upstream. - When should in-memory Python code store records as a list of dicts versus a dict of lists? A
listofdicts ([{"id": 1, "value": 2.5}, ...]) is natural when streaming or validating one self-contained record at a time, because each record is created and discarded immediately. If you keep millions of rows in RAM at once, paying~200+bytes for a separatedictper row wastes gigabytes; a columnardictoflists ({"id": [...], "value": [...]}) — or NumPy/Arrow arrays — stores column names once, packs pointers/numbers contiguously for CPU cache locality, and uses a fraction of the memory. - What changes if exact cent-level monetary totals are required instead of 64-bit floats? Binary
float64cannot represent0.10exactly (0.1 + 0.2 == 0.30000000000000004) and loses integer precision past2^53(~9 * 10^15). For monetary columns, parse strings withdecimal.Decimal(base-10 arithmetic with configurable precision and explicitInvalidOperation/Overflowtraps) or convert fixed-scale currency strings directly into integer minor units (cents) summed as arbitrary-precision Pythonints.
Follow-up questions
- How would you parallelize summing a multi-gigabyte file across 8 CPU cores?
- When should in-memory Python code store records as a list of dicts versus a dict of lists?
- What changes if exact cent-level monetary totals are required instead of 64-bit floats?
Similar questions
- Time-Zone Weekly Totals and 3-Week Rolling Sums
- Category Response Rates with Invitation Weighting
- Marketplace Provider-Ranking Experiment Design
- Simulating Stay and Switch Win Rates
- Numerically Stable Min, Mean, and Median
- Driving a 72-Hour Executive Rollout Recommendation Across Teams
More Thumbtack interview questions
- Time-Zone Weekly Totals and 3-Week Rolling Sums Medium
- Category Response Rates with Invitation Weighting Medium
- Marketplace Provider-Ranking Experiment Design Hard Pro
- Simulating Stay and Switch Win Rates Medium Pro
- Numerically Stable Min, Mean, and Median Medium Pro
- Driving a 72-Hour Executive Rollout Recommendation Across Teams Hard Pro
- Modeling Adjusted Regional Response-Rate Differences Medium Pro