8. Zip Columns into Records
Difficulty: Easy · Topic: Core Python & data structures
An export arrives as three parallel lists: ids, names and cities, where position i of each list belongs to the same rider. Write to_records(ids, names, cities): return a list of dicts with the keys 'id', 'name' and 'city', one per position, in order.
- If the three lists do not all have the same length, the export is broken: raise
ValueErrorinstead of returning partial records. - Values are copied as they are, including
None. The inputs may be any sequences (lists or tuples).
Example: to_records([1, 2], ['asha', 'ben'], ['Pune', 'Goa']) gives [{'id': 1, 'name': 'asha', 'city': 'Pune'}, {'id': 2, 'name': 'ben', 'city': 'Goa'}].
Your code runs in CPython on our servers against 6 tests, including hidden ones.
Sample test
to_records([1, 2], ['asha', 'ben'], ['Pune', 'Goa'])Expected: [{'id': 1, 'name': 'asha', 'city': 'Pune'}, {'id': 2, 'name': 'ben', 'city': 'Goa'}]
Hints
Hint 1
zip(a, b, c) walks the three lists side by side.Hint 2
Plainzip stops at the shortest list without telling you. One keyword argument makes it raise instead.Learn the concepts
- Strings and built-in functions · 6 min read. split, join, strip, f-strings, zip, enumerate, any, all, min, max and sorted, and their surprises.
More Python problems
- Flatten a Nested List · Easy
- Squares of the Even Numbers · Easy
- Top K Frequent Words · Easy
- Invert a Dictionary · Easy
- Merge Dicts and Sum Shared Keys · Easy
- Group Records by Key · Easy
- Count Words in Reviews · Easy
- Find the Missing IDs · Easy
- Safe Min and Max · Easy
- Sort by Several Keys · Medium
- Fix the Mutable Default Argument · Medium
- Override a Config Without Changing It · Medium
- Keep the Last N Events · Medium