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"}):

  1. parse_value(raw) -> Optional[float]

    • Converts a single raw cell or JSON primitive into a finite float, or returns None if raw represents a missing entry.
    • Missing entries: None, floating-point NaN, or a string whose .strip().lower() matches MISSING_TEXT.
    • Invalid entries (ValueError): Any non-numeric text (such as "oops"), booleans (True or False), containers (list, dict), infinities ("inf", float("inf")), or numbers exceeding IEEE-754 float64 range ("1e400", 10**400).
  2. 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 with U+FFFD (errors="replace").
    • Ignores empty or whitespace-only lines completely.
    • Increments "missing" when field is omitted from the JSON object or parse_value returns None.
    • Increments "bad" when json.loads fails (syntax errors, oversized integer literals, or excessive nesting depth), when the decoded JSON value is not a dict, or when parse_value raises ValueError.
    • Raises OverflowError if the accumulated "total" overflows float64.
  3. sum_csv(byte_lines: Iterable[bytes], column: str = "value") -> Dict

    • Streams a headered CSV byte-line iterable via csv.DictReader using the same UTF-8 decoding, blank-line skipping, return dictionary structure, and running-sum OverflowError check as sum_jsonl.
    • Raises ValueError if the file has no valid header row or column is absent from the header.
    • Increments "bad" whenever csv raises csv.Error on a record, when a row has fewer or more fields than the header (even if column itself was already populated earlier in the row), or when parse_value rejects the cell in column.

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_lines may 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 a float (7.0), while parse_value(True) and parse_value(False) must raise ValueError. Individual overflowing cells (1e400, 10**400) count as "bad", whereas valid cells whose running sum overflows float64 (1e308 + 1e308) must raise OverflowError.
  • Empty inputs: An empty or blank-only JSON Lines stream returns {"total": 0.0, "used": 0, "missing": 0, "bad": 0}. An empty CSV stream raises ValueError (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

  1. Python list vs dict: operations, Big-O, memory, and ordering

    In CPython 3, a list is a dynamic array (a single contiguous block of memory storing 8-byte pointers to Python objects, indexed by integer position 0 .. n-1). A dict is an open-addressed hash table (a sparse index array pointing into a compact table of [hash, key_ptr, value_ptr] entries, indexed by hash(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) resize d[k] = v (new key): O(1) average / O(n) collision or resize
    Insert at position i lst.insert(i, x): O(n - i) average and worst Not 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) worst
    Update existing lst[i] = x: O(1) average and worst d[k] = v (existing key): O(1) average / O(n) worst
    Delete 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) worst

    Why 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 roughly 12.5% larger and copies all n pointers (O(n) once), spreading out to O(1) amortized cost per append. Inserting or popping at index 0 shifts all n pointers every single call (O(n)), which is why queues use collections.deque instead.
    • Hash collisions and table resizes (dict): Looking up d[k] jumps straight to hash(k) % table_size in O(1) on average. If adversarial or buggy keys all share the same hash (hash collision), CPython must probe O(n) slots per lookup (mitigated for strings by per-process hash randomization via PYTHONHASHSEED). Once the sparse index table reaches 2/3 full, the next new key triggers an O(n) rebuild.
    • Memory footprint (64-bit CPython 3): A 1,000,000-element list container takes about 8.0-8.5 MB (8 bytes per pointer + small header + ~12.5% spare slots), whereas a 1,000,000-entry dict container takes roughly 31-42 MB (3.5-5x larger) because each entry stores hash + key + value (24 bytes, or 16 bytes for compact all-str keys 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: list preserves positional order. Since Python 3.7, dict preserves insertion order by language specification (in CPython 3.6 it was an implementation side effect): overwriting an existing key d[k] = new_v keeps its original position, while del d[k] followed by d[k] = new_v moves k to 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
    
  2. 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 forbids NaN, 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 distinguish NULL from an empty string "" without out-of-band conventions.
    • Size, compression, and analytics: Choose CSV for flat, fixed-schema tables exchanged with spreadsheets or COPY bulk-loaders — writing column names once makes uncompressed CSV roughly 2.5-3x smaller than JSON Lines. Under gzip or zstd, dictionary compression collapses repeated JSON keys so compressed JSON Lines shrinks to within ~1.15x of compressed CSV (note that a single .gz stream 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.
  3. 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 (None returned): Python None, floating-point NaN, or any case/whitespace variation of "", "na", "n/a", "nan", "null", "none".
    • Invalid or overflowing cells (ValueError raised):
      1. Check isinstance(raw, bool) before (int, float) because bool subclasses int in Python — otherwise True silently adds 1.0 to your sum!
      2. float(10**400) raises OverflowError (not ValueError), so catch and convert it to ValueError.
      3. float("1e400") and Python's json.loads("1e400") do not raise; they silently return +inf! Checking math.isinf(number) catches "1e400" and "inf" before a single bad row turns the entire sum into inf.
    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
    
  4. Track row counts, cap warnings, and decode UTF-8 safely

    Every non-blank record lands in exactly one bucket — used, missing, or bad — so a production job can assert data completeness and alert if the bad fraction spikes, while MAX_LOGGED = 10 keeps 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 with UnicodeDecodeError on the first stray Latin-1 byte (\xe9 or \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\xbf added by Excel/Windows exports, which would otherwise turn header "value" into "\ufeffvalue" or break json.loads), then switch to "utf-8" for line 2+.
    • Pass errors="replace" so undecodable bytes become the Unicode replacement character U+FFFD (`). If the stray byte was inside an unusednamecolumn, the numericvaluestill sums cleanly; if it hitvalue,parse_valuerejects it asbad`.
    • Finally, finish() checks math.isfinite(stats["total"]) so two valid floats whose running sum overflows float64 (1e308 + 1e308 -> inf) raise OverflowError.
    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"
    
  5. Stream JSON Lines line by line with sum_jsonl

    Iterating directly over open("data.jsonl", "rb") yields one line at a time, holding only O(longest line) in RAM regardless of whether the file is 10 MB or 10 TB. Around json.loads(line), catch (ValueError, RecursionError) rather than only json.JSONDecodeError: in Python 3.11+, a 5,000-digit integer triggers sys.set_int_max_str_digits and raises a plain ValueError, while 100,000 nested [ brackets raise RecursionError. Also verify isinstance(record, dict) so valid non-object JSON lines like [1, 2] are counted as bad, while an absent key (record.get(field) returning None) counts as missing for 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)
    
  6. Stream CSV with csv.DictReader and sum_csv (the non-pandas alternative)

    csv.DictReader consumes our decode_lines generator one record at a time using only the Python standard library — making sum_csv our safe, zero-dependency non-pandas streaming alternative. Because decode_lines preserves \r\n and \n line endings, quoted multi-line cells like "two\r\nlines" stay intact as one record.

    Notice how csv.DictReader signals ragged rows in the dictionary it yields for header tx_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) inside while True also lets us catch csv.Error (such as a single corrupt field exceeding csv.field_size_limit(), 131,072 chars) 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 the 131,072-char limit, so always compare used + missing + bad against 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)
    
  7. Stream with pandas chunksize and size chunks for 10 GB on 16 GB RAM

    With pandas, passing chunksize to pd.read_csv returns a lazy iterator of DataFrames so only one chunk resides in RAM at a time. Read 'value' as str first so a single "abc" cell cannot crash C-engine float parsing for the entire chunk, coerce with pd.to_numeric(..., errors="coerce"), and guard against both cell-level inf ("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 int64 sums on untrusted integers in NumPy/pandas: unlike Python int, int64 overflows 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,000 rows), which spend more time in Python loop/DataFrame construction overhead than in C-level parsing.

  8. Complete solution

    Putting parse_value, the shared counting and UTF-8 line-decoding helpers, sum_jsonl, and sum_csv together into solution.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:

  1. \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) returns 15.5 -> total = 15.5, used = 1.
  2. {"event": "d", "value": " n/a "} -> strip().lower() matches MISSING_TEXT -> parse_value returns None -> missing = 1.
  3. {"event": "e", "value": false} -> rejected because bool subclasses int in Python -> bad = 1 (logged with line number).
  4. {"event": "f", "value": 1e400} -> float parses to inf, caught by math.isinf -> bad = 2 (total stays 15.5, uncorrupted).
  5. {"event": "b", "value": " -3.25 "} -> parse_value(" -3.25 ") returns -3.25 -> finish() verifies total = 12.25 is finite and returns {"total": 12.25, "used": 2, "missing": 1, "bad": 2}.

Complexity

  • Time — O(B) across B input bytes: Both sum_jsonl and sum_csv decode each byte once in decode_lines, parse each line once with json.loads or csv.DictReader, and perform constant-time (O(1)) hash-set and float checks per record. For list vs dict operations, list.append is amortized O(1) (an occasional O(n) pointer copy when capacity fills averages out to constant time per append) and list.insert(i, x) / pop(i) is O(n - i) from shifting trailing pointers, whereas dict lookup/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 length L bytes plus a 4-key stats dictionary (O(1)), so memory never grows with row count. Chunked pandas.read_csv allocates one DataFrame chunk at a time (~600 MB at chunksize=1_000_000 for 600-byte in-memory rows, comfortably inside 16 GB RAM).

Edge cases

  • Leading UTF-8 BOM (\xef\xbb\xbf): Stripped on line 1 only via "utf-8-sig" so CSV headers are "value" (not "\ufeffvalue") and line 1 of JSONL parses cleanly.
  • Windows \r\n and multi-line CSV quotes: Keeping raw line endings when feeding csv.DictReader allows "two\r\nlines" inside quotes to be assembled as a single CSV record without leaving stray \r characters on numbers.
  • Ragged CSV rows regardless of column order: With header id,value,name, a short row 2,7 already populated value="7", yet None in row.values() still catches the missing name column and marks the row bad. Extra fields land under key None (None in row).
  • Malformed/oversized CSV headers or rows: Stepping next(reader) inside try ... except csv.Error catches rows exceeding csv.field_size_limit() (131,072 characters), and wrapping reader.fieldnames converts broken headers into ValueError.
  • Hostile JSON literals: Python's json.loads accepts non-standard NaN (treated as missing) and Infinity (rejected as bad), raises plain ValueError on integers past 4,300 digits, and raises RecursionError on deep [ nesting — all caught safely without stopping the stream.
  • Booleans and running-sum overflow: True/False are rejected before int checks; individual overflows (1e400, 10**400) count as bad, while a running total overflowing float64 (1e308 + 1e308) raises OverflowError.
  • Corrupt encodings and unclosed CSV quotes: errors="replace" turns bad bytes into U+FFFD so bad text in other columns never drops a valid numeric value. An unclosed CSV quote consumes lines until the next quote or the 131,072-char limit; comparing used + missing + bad against physical line count detects swallowed rows.

Common mistakes

  • Calling f.read(), f.readlines(), json.load(f), or list(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 \xff byte throws UnicodeDecodeError halfway through a 10 GB job.
  • Catching only json.JSONDecodeError around json.loads (missing plain ValueError on huge integers and RecursionError on deep nesting), or wrapping the entire file loop in one try/except instead of per-row error handling.
  • Forgetting isinstance(raw, bool) before isinstance(raw, int) or forgetting math.isinf(float(x)), allowing True (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 to pd.read_csv on messy data (one "abc" aborts the whole chunk) instead of reading strings and calling pd.to_numeric(..., errors="coerce").
  • Expecting del d[k] to release a Python dict's hash-table memory, or using x in my_list (O(n)) repeatedly inside a loop instead of a set/dict (O(1) average).

Alternative approaches

  • High-precision floating-point summation (math.fsum / Kahan summation): Standard total += value can accumulate rounding drift across 10^8 rows when huge and tiny numbers mix. Kahan summation (tracking a small running compensation term for lost low-order bits) or Python's math.fsum preserves full precision in O(1) extra memory.
  • Dead-letter queue + bad-row budget: Write malformed raw lines and line numbers to a separate bad_rows.jsonl side file for replay, and fail the pipeline at the end if bad / (used + missing + bad) exceeds a threshold such as 0.1%.
  • Convert once to Parquet with DuckDB or PyArrow: Streaming CSV/JSONL into typed, zstd-compressed Parquet lets every downstream query scan only the value column 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 8 byte ranges [start, end), have each worker seek to start and advance past the first \n (except worker 0, which reads the header first), and sum its slice independently before adding the 8 {total, used, missing, bad} dicts together. If the CSV may contain quoted multi-line fields or single-stream .gz compression, 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 list of dicts ([{"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 separate dict per row wastes gigabytes; a columnar dict of lists ({"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 float64 cannot represent 0.10 exactly (0.1 + 0.2 == 0.30000000000000004) and loses integer precision past 2^53 (~9 * 10^15). For monetary columns, parse strings with decimal.Decimal (base-10 arithmetic with configurable precision and explicit InvalidOperation/Overflow traps) or convert fixed-scale currency strings directly into integer minor units (cents) summed as arbitrary-precision Python ints.

Follow-up questions

Similar questions

More Thumbtack interview questions

All 8 Thumbtack questions →