Hash join two lists of dicts
Python data engineering interview problem. Difficulty: intermediate. Pattern: Dictionaries. About 16 minutes. Part of the Pro drill bank.
Join two lists of dictionaries on a shared key field, supporting both inner and left join modes. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.
Implement hash_join(left: list[dict], right: list[dict], on: str, how: str = "inner") -> list[dict] to join two lists of records. on: the shared key attribute present in the dictionaries. how="inner": return joined dictionaries only for records whose on value matches across both collections. how="left": include every record from left. If a record from left has matching records in right, produce a joined record for each match. If it has no match, return a copy of the left record. If multiple records in right share the same on key, each matching right record joins with the left record. The input lists must not be modified.
Requirements
- Do not mutate the input lists or dictionaries.
- Support both 'inner' and 'left' join semantics.
Constraints
- 1 <= len(left), len(right) <= 50,000
- on is guaranteed to be a string key.
- how is either 'inner' or 'left'.
Examples
Input: hash_join([{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}], [{'id': 1, 'dept': 'Eng'}], 'id', 'inner') Output: [{'id': 1, 'name': 'Alice', 'dept': 'Eng'}] Only id 1 matches across both lists, producing one joined record.
Topics: lakebench, python, hash-join, inner-left.
More Python interview questions · All interview problems · Learn data engineering
Hash join two lists of dicts
Interview-style drill: Join two lists of dictionaries on a shared key field, supporting both inner and left join modes.
Implement `hash_join(left: list[dict], right: list[dict], on: str, how: str = "inner") -> list[dict]` to join two lists of records. - `on`: the shared key attribute present in the dictionaries. - `how="inner"`: return joined dictionaries only for records whose `on` value matches across both collections. - `how="left"`: include every record from `left`. If a record from `left` has matching records in `right`, produce a joined record for each match. If it has no match, return a copy of the `left` record. - If multiple records in `right` share the same `on` key, each matching `right` record joins with the `left` record. - The input lists must not be modified.