CSV Transaction Parser with Validation and Error Handling
StringsModel answerLast updated
Design a pipeline that parses CSV transaction records, normalizes fields, validates data integrity, and segregates malformed entries.
Problem Statement
Design and implement a function that processes raw transaction records provided as CSV strings. The pipeline must parse each record, apply normalization rules, validate data integrity, and maintain an audit trail of rejected entries.
Your function signature is:
def process_transactions(raw_data: list[str]) -> dict
The function should return a dictionary with two keys:
"cleaned": a list of validated transaction dictionaries"rejected": a list of raw strings that failed validation
Each input string represents one CSV row with four columns: transaction_id, timestamp, amount, currency.
Requirements
Parsing
- Use proper CSV parsing to handle quoted fields and embedded commas
- Each row must contain exactly four fields
- Skip any header row (identified by column names matching the expected fields)
Normalization
- Strip leading and trailing whitespace from all fields
- Handle currency symbols embedded in amounts (e.g.,
$100.50should extract100.50and inferUSD) - Recognize common currency aliases:
$,US$,€,£, etc., and map them to standard three-letter codes - Preserve at least two decimal places for all amounts (pad if necessary, never round)
Validation
- Reject rows where
transaction_idis missing or empty after trimming - Reject rows where
amountis not a valid decimal number - Reject rows with non-finite amounts (
NaN,Infinity) - Reject rows where currency cannot be resolved to a valid three-letter code
- Reject duplicate transaction IDs (first occurrence wins)
- Reject rows with conflicting currency indicators (e.g.,
$100in the amount field butEURin the currency field)
Precision
- Use exact decimal arithmetic to avoid floating-point errors
- Return amounts as strings formatted with fixed-point notation (no scientific notation)
Error Handling
- Never allow a single malformed row to crash the entire pipeline
- Preserve the original raw string for every rejected entry
Example
Input:
[
"transaction_id,timestamp,amount,currency",
"tx_001,2023-10-01,100.50,USD",
"tx_002,2023-10-01,invalid,USD",
",2023-10-01,50.00,EUR",
"tx_003,2023-10-01, 75.25 , EUR ",
"tx_004,2023-10-02,$99.99,",
"tx_001,2023-10-02,200.00,USD"
]
Expected output:
{
"cleaned": [
{"transaction_id": "tx_001", "timestamp": "2023-10-01", "amount": "100.50", "currency": "USD"},
{"transaction_id": "tx_003", "timestamp": "2023-10-01", "amount": "75.25", "currency": "EUR"},
{"transaction_id": "tx_004", "timestamp": "2023-10-02", "amount": "99.99", "currency": "USD"}
],
"rejected": [
"tx_002,2023-10-01,invalid,USD",
",2023-10-01,50.00,EUR",
"tx_001,2023-10-02,200.00,USD"
]
}
Constraints
- Use Python standard library only
- Output must be deterministic (same input always produces same output, same order)
- Negative amounts are allowed (they represent refunds or reversals)
Hints
Hint 1
Use Python's csv module to handle quoted fields and commas correctly
Hint 2
The Decimal class from the decimal module provides exact arithmetic for currency values
Hint 3
Structure your validation as independent checks that each raise a specific exception when violated
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Approach
The core strategy is to build a three-stage pipeline for each row: parse the raw string into fields, normalize those fields into a standard format, then validate business rules. Any failure at any stage sends the original raw line to the rejected collection. This keeps the pipeline robust—one bad row never stops processing.
Stage 1: Parsing
Use csv.reader instead of naive string splitting. This correctly handles edge cases like quoted fields containing commas ("tx_5","2023-10-01","1,000.00",USD). Verify the row has exactly four fields. Skip any row that looks like a header by comparing field names case-insensitively.
Stage 2: Normalization
- Trim whitespace from every field
- Extract currency symbols from the amount field itself (e.g.,
$100becomes amount100and inferred currencyUSD) - Map free-form currency labels to three-letter ISO codes using an alias table:
$→USD,€→EUR,£→GBP, etc. - Parse the amount using
Decimalfor exact precision. If the value has fewer than two decimal places, pad it (e.g.,100.5becomes100.50). Never round—rounding would silently discard data.
Stage 3: Validation
Run independent checks in sequence:
- Transaction ID must be non-empty after trimming
- Transaction ID must not have appeared in any previously accepted row
- Amount must be a finite decimal number (reject
NaN,Infinity, and non-numeric strings) - Currency must resolve to a valid three-letter alphabetic code
- If a currency symbol was embedded in the amount, and a different currency is in the currency field, reject for conflict
Each check raises a custom RowError exception when violated. The driver loop catches any exception and routes the raw line to rejected.
Key Design Decisions
Return rejected rows as raw strings
An auditor or downstream repair process needs the original input to understand what went wrong. Returning a parsed structure would lose information.
First duplicate ID wins
Only add the transaction ID to the "seen" set after the row fully passes validation. This means a rejected row doesn't block a later valid row with the same ID. The first valid occurrence is kept; subsequent duplicates are rejected.
Determinism
Never iterate over sets when building output. Process rows in input order. Use no randomness, no timestamps, no filesystem ordering.
Exact arithmetic
Use Decimal throughout. Parsing "0.1" as a Decimal is exact; parsing as float introduces representation error. Format with format(value, "f") to avoid scientific notation in the output.
Complexity
- Time: O(N · L) where N is the number of rows and L is the average row length. Each row is parsed once, and ID lookups in the seen set are O(1).
- Space: O(N) for the output lists and the set of seen IDs.
Edge Cases and Common Mistakes
- Empty or whitespace-only ID: Caught by the non-empty check after trimming
- Wrong field count: A trailing comma creates an extra empty field; a missing column leaves too few. Both are rejected during parsing.
- Whitespace in numeric fields:
" 75.25 "is trimmed before parsing - Invalid amounts:
"invalid","","12.3.4","NaN","inf"all failDecimalparsing or the finite check - Conflicting currency:
$100in the amount withEURin the currency field is rejected - Non-string input: If
raw_datacontains a non-string element, wrap parsing in a type check - Very large amounts: Values exceeding
Decimal's precision during quantize will raise an exception, which is caught and rejected
A common mistake is using float for currency. float(0.1) + float(0.2) != 0.3 due to binary representation. Another mistake is silently rounding amounts, which hides precision loss.
Implementation
import csv
from decimal import Decimal, InvalidOperation
FIELDS = ("transaction_id", "timestamp", "amount", "currency")
TWO_PLACES = Decimal("0.01")
CURRENCY_ALIASES = {
"$": "USD", "US$": "USD", "DOLLAR": "USD",
"€": "EUR", "EURO": "EUR",
"£": "GBP", "POUND": "GBP",
}
AMOUNT_SYMBOLS = {"$": "USD", "€": "EUR", "£": "GBP"}
class RowError(ValueError):
"""Raised when a row fails validation."""
def _parse_fields(line):
if not isinstance(line, str):
raise RowError("not a string")
rows = list(csv.reader([line], skipinitialspace=True))
if len(rows) != 1 or len(rows[0]) != len(FIELDS):
raise RowError("wrong field count")
return [field.strip() for field in rows[0]]
def _is_header(line):
try:
fields = _parse_fields(line)
return tuple(f.lower() for f in fields) == FIELDS
except RowError:
return False
def _normalize_amount(text):
symbol_currency = None
if text[:1] in AMOUNT_SYMBOLS:
symbol_currency = AMOUNT_SYMBOLS[text[0]]
text = text[1:].strip()
try:
value = Decimal(text)
if not value.is_finite():
raise RowError("non-finite amount")
if value.as_tuple().exponent > -2:
value = value.quantize(TWO_PLACES)
except InvalidOperation:
raise RowError("invalid amount")
return format(value, "f"), symbol_currency
def _normalize_currency(text):
code = text.strip().upper()
return CURRENCY_ALIASES.get(code, code)
def _clean_row(line):
tx_id, timestamp, amount_text, currency_text = _parse_fields(line)
amount, symbol_currency = _normalize_amount(amount_text)
currency = _normalize_currency(currency_text)
if symbol_currency:
if currency and currency != symbol_currency:
raise RowError("conflicting currency")
currency = symbol_currency
return {
"transaction_id": tx_id,
"timestamp": timestamp,
"amount": amount,
"currency": currency
}
def _validate_row(record, seen_ids):
if not record["transaction_id"]:
raise RowError("missing ID")
if record["transaction_id"] in seen_ids:
raise RowError("duplicate ID")
code = record["currency"]
if len(code) != 3 or not code.isalpha():
raise RowError("invalid currency code")
def process_transactions(raw_data):
cleaned = []
rejected = []
seen_ids = set()
for line in raw_data:
if _is_header(line):
continue
try:
record = _clean_row(line)
_validate_row(record, seen_ids)
seen_ids.add(record["transaction_id"])
cleaned.append(record)
except (RowError, csv.Error):
rejected.append(line)
return {"cleaned": cleaned, "rejected": rejected}
This implementation handles all specified requirements and edge cases while maintaining clean separation between parsing, normalization, and validation logic.