CODING CHALLENGE · N°59

CSV → Schema Mapper

Medium FDEDataIntegrations

Every customer hands you a messy export. Before it can flow into your system, each row must be coerced to a schema — strings to ints, "true" to booleans — and the rows that don’t fit quarantined, not silently dropped. Build the mapper. Solve it in Python or TypeScript, with hidden tests.

The problem

Implement map_rows(rows, schema). rows is a list of dicts (parsed CSV records) and schema maps each required field name to a type: "int", "float", "bool", or "str". For each row, coerce every schema field to its type. A row is valid only if all schema fields are present and every value coerces; otherwise it counts as an error. Return {"valid": [coerced rows], "errors": count}.

EXAMPLE 1
Input rows = [{"age":"30","name":"al"},{"age":"x","name":"bo"},{"name":"cy"}], schema = {"age":"int","name":"str"}
Output {"valid": [{"age": 30, "name": "al"}], "errors": 2}
row 2 fails coercion ("x"→int), row 3 is missing "age"
CONSTRAINTS
  • Coerce: int("30")→30, float("1.5")→1.5, bool: "true"/"1"→True, "false"/"0"→False (anything else fails), str: leave as-is.
  • A missing schema field or a failed coercion makes the whole row an error (not partially valid).
  • Preserve field order as given in the schema; return the count of error rows, not the rows themselves.
SOLVE IT YOURSELF

Your turn — write it

Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.

YOUR TASK

Implement map_rows(rows, schema): for each row try to build a coerced record over the schema fields; on any missing field or bad value, count it as an error instead.

HINTS — 4 IDEAS
  1. Write a coerce(value, type) helper that raises/throws on a bad value.
  2. For each row, loop the schema fields in order; if a field is missing or coercion fails, mark the row an error.
  3. Booleans are the tricky type: only a small set of strings are valid; everything else fails.
  4. Return the valid coerced rows and just the count of errors.
CPython · WebAssembly

Explore the topic

See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.