Skip to content

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:

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 1Build a dict from join value to the list of right rows: a hash join, O(len(left) + len(right)).
Hint 2Work out the right column names (with suffixes) once, before the loop.
Hint 3None keys must be left out of the index.

Learn the concepts

More Python problems

All Python problems