Editor

Join Two Tables

#304 · Working with data · Intermediate · 70 XP · about 14 min

Two lists of records (dictionaries), such as orders and customers, share a field, for example 'customer_id'. Write inner_join(left, right, key) that joins them the way a database does: for every pair of a record from left and a record from right with the same value in the field key, make one new dictionary holding the fields of both. Return the list of these joined dictionaries. Records with no match on the other side are left out.

  • Order of the results: go through left in order, and for each record take its matches in the order they appear in right.
  • Fields of a joined record: the left record's fields first, in their order, then the right record's fields that the left one does not have, in their order. When both records have a field with the same name, the value from the right record wins.
  • Do not change the input lists or their dictionaries.

Examples

orders = [
    {'order': 1, 'customer_id': 7, 'total': 30},
    {'order': 2, 'customer_id': 9, 'total': 12},
    {'order': 3, 'customer_id': 7, 'total': 5},
]
customers = [
    {'customer_id': 7, 'name': 'Ana'},
    {'customer_id': 8, 'name': 'Bo'},
]
inner_join(orders, customers, 'customer_id')
# returns [{'order': 1, 'customer_id': 7, 'total': 30, 'name': 'Ana'},
#          {'order': 3, 'customer_id': 7, 'total': 5, 'name': 'Ana'}]

Order 2 has no customer 9 to match, and customer 8 has no orders, so neither appears.

Constraints

  • Each list holds up to 5,000 records, and every record has the field key.
  • Key values are whole numbers or strings.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.