Skip to content

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:

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 1csv.DictReader reads quoted fields correctly and keys each row by the header, whatever the column order.
Hint 2It needs a file-like object: io.StringIO(text) wraps a string as one.
Hint 3Every value it returns is a string. Convert with int and float, and check for an empty fare first.

Learn the concepts

More Python problems

All Python problems