CSV → Schema Mapper
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}.
rows = [{"age":"30","name":"al"},{"age":"x","name":"bo"},{"name":"cy"}], schema = {"age":"int","name":"str"}{"valid": [{"age": 30, "name": "al"}], "errors": 2}- 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.
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.
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.
- Write a
coerce(value, type)helper that raises/throws on a bad value. - For each row, loop the schema fields in order; if a field is missing or coercion fails, mark the row an error.
- Booleans are the tricky type: only a small set of strings are valid; everything else fails.
- Return the valid coerced rows and just the count of errors.
Explore the topic
See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.