easy +8 pts

Inner Join Two Tables

Implement a function that performs an inner join on two lists of dictionaries using a common key.

Write a function `inner_join(left, right, key)` that takes two lists of dictionaries `left` and `right`, and a string `key` that exists in all dictionaries of both lists. The function should perform an inner join on the given key, meaning: for every pair of dictionaries (one from `left`, one from `right`) where `left_dict[key] == right_dict[key]`, produce a new dictionary that contains all the keys from the left dictionary and all the keys from the right dictionary (excluding the duplicate key, since it's the same). The resulting list should be sorted by the value of the shared `key` in ascending order. If there are multiple pairs with the same key, they should appear in the order they were encountered: first by the position in `left`, then by the position in `right`. If either list is empty or there are no matching keys, return an empty list.

Constraints

Input lists have at most 1000 dictionaries each. All dictionaries are flat (no nested dicts or lists as values). The `key` is a string that is present in every dictionary of both lists. Values for the key are comparable and hashable (e.g., int, str).

Example

>>> left = [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}]
>>> right = [{'id': 2, 'score': 90}, {'id': 1, 'score': 85}]
>>> inner_join(left, right, 'id')
[{'id': 1, 'name': 'Alice', 'score': 85}, {'id': 2, 'name': 'Bob', 'score': 90}]

>>> left = [{'id': 1, 'name': 'Alice'}]
>>> right = [{'id': 2, 'name': 'Bob'}]
>>> inner_join(left, right, 'id')
[]
8 points ~12 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Iterate over left and right lists in nested loops.
To avoid duplicate key, copy the left dict and then update with the right dict after removing the key.
Sort the result by the key value after building the list.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.