Safely parse a batch of numeric strings
Python data engineering interview problem. Difficulty: intermediate. Pattern: Strings. About 15 minutes. Part of the Pro drill bank.
A CSV column is supposed to be numeric but contains junk. Ingest should convert what it can and skip or default the rest without crashing the job.
Data from forms and files often has numbers stored as text, and some of it is not a number at all. A loader should not crash on bad values. Try to turn each value into a float. Put the good floats in ok and the values that cannot be converted in bad, unchanged. Return a dictionary with both lists. Write parse_numbers(values). For ['1', '2.5', 'no'] the result is {'ok': [1.0, 2.5], 'bad': ['no']}. For an empty list both lists are empty. The starter file already has the function name and its print lines. Keep them and fill in the body.
Requirements
- Convert each value with float.
- Collect the converted values in ok.
- Collect the values that fail in bad, as they were.
- Do not stop at the first bad value.
Constraints
- values is a list. Items are usually strings but can be other types.
- The result is {'ok': [...], 'bad': [...]}.
Examples
Input: parse_numbers(['1', '2.5', 'no']) Output: {'ok': [1.0, 2.5], 'bad': ['no']} This input follows the stated rules and produces this output.
Topics: lakebench, python, error-handling.
More Python interview questions · All interview problems · Learn data engineering
Safely parse a batch of numeric strings
Interview-style drill: Convert a list of strings to numbers, collecting which entries failed instead of crashing.
Safely parse a batch of numeric strings.