41. Left Join Two Lists of Dicts
Difficulty: Medium · Topic: Data wrangling
Write left_join(left, right, on) for two lists of dicts (rows), joined where row[on] is equal:
- Every left row appears at least once, in the original order. A left row with several matches appears once per match, in the order of
right. - A left row with no match gets every right column set to
None. The right columns are all keys that appear in any right row, excepton, in first-seen order. - If a right column has the same name as a left column, it is renamed with the suffix
_right. - Rows whose
onvalue isNonenever match, as in SQL. - It must be fast: index the right side instead of scanning it for every left row.
Your code runs in CPython on our servers against 6 tests, including hidden ones.
Sample test
orders = [{'oid': 1, 'cid': 'a'}, {'oid': 2, 'cid': 'b'}, {'oid': 3, 'cid': 'z'}]
customers = [{'cid': 'a', 'name': 'Asha'}, {'cid': 'b', 'name': 'Ben'}]
left_join(orders, customers, 'cid')Expected: [{'oid': 1, 'cid': 'a', 'name': 'Asha'}, {'oid': 2, 'cid': 'b', 'name': 'Ben'}, {'oid': 3, 'cid': 'z', 'name': None}]
Hints
Hint 1
Build a dict from join value to the list of right rows: a hash join, O(len(left) + len(right)).Hint 2
Work out the right column names (with suffixes) once, before the loop.Hint 3
None keys must be left out of the index.Learn the concepts
- Wrangling data without pandas · 5 min read. Parse, flatten, deduplicate, join and aggregate in plain Python, with SQL's null rules.
More Python problems
- Parse Log Lines into Records · Easy
- Reformat Date Strings · Easy
- CSV Rows to Typed Records · Easy
- Flatten Nested JSON · Medium
- Keep the Latest Record per Key · Medium
- Group and Aggregate without pandas · Medium
- Merge Overlapping Sessions · Hard
- Schema Validation with a Dead-Letter Queue · Hard