37. CSV Rows to Typed Records
Difficulty: Easy · Topic: Data wrangling
Write parse_trips(text): text is the content of a CSV file whose header names the columns trip_id, city and fare (in any order). Return one dict per data row, in order, with:
'trip_id': anint;'city': the text with spaces around it removed. A city may contain a comma, in which case the CSV quotes it, like"Navi Mumbai, MH";'fare': afloat, orNonewhen the field is empty or only spaces.
Completely blank lines are skipped. A file with only the header gives [].
Example: parse_trips("trip_id,city,fare\n1,Pune,120.5\n") gives [{'trip_id': 1, 'city': 'Pune', 'fare': 120.5}].
Your code runs in CPython on our servers against 5 tests, including hidden ones.
Sample test
parse_trips("trip_id,city,fare\n1,Pune,120.5\n2,Goa,80\n")Expected: [{'trip_id': 1, 'city': 'Pune', 'fare': 120.5}, {'trip_id': 2, 'city': 'Goa', 'fare': 80.0}]
Hints
Hint 1
csv.DictReader reads quoted fields correctly and keys each row by the header, whatever the column order.Hint 2
It needs a file-like object:io.StringIO(text) wraps a string as one.Hint 3
Every value it returns is a string. Convert withint and float, and check for an empty fare first.Learn the concepts
- Files, JSON, CSV and dates · 8 min read. Read files line by line, JSON and CSV, ISO dates, strptime codes, time zones and zoneinfo.
More Python problems
- Parse Log Lines into Records · Easy
- Reformat Date Strings · Easy
- Flatten Nested JSON · Medium
- Keep the Latest Record per Key · Medium
- Group and Aggregate without pandas · Medium
- Left Join Two Lists of Dicts · Medium
- Merge Overlapping Sessions · Hard
- Schema Validation with a Dead-Letter Queue · Hard