Joining Records on a Shared Key

Concepts covered: List Comprehension

Plays and track details usually live in separate lists. Each play stores only a track_id, while the track's title and artist sit in a catalog list that names each track a single time. Joining pairs them up: for every play, find the catalog record with the same track_id and combine the fields you need into a single row. The field both sides share is the join key.

The nested-loop join

The direct approach puts a loop inside a loop: for each play, walk the whole catalog and keep the track whose key matches. It produces correct rows, and it compares every play against every track. The 4 plays and 2 tracks above take 8 comparisons. Now picture a day of 1,000,000 plays against a catalog of 100,000 tracks: at Python speeds, that product is hours of work.

for play in plays:
    for track in tracks:
        if track["track_id"] == play["track_id"]:
            print(play["play_id"], track["title"])

Build an index once, then look up

A dict goes straight to the value stored under a key without walking the other entries. So spend 1 pass over the catalog building index, a dict that maps each track_id to its track record. Then make 1 pass over the plays, each doing a single index.get(play["track_id"]). Because .get returns None for a missing key, a play that points at an unknown track shows up as a missing match instead of stopping the loop with a KeyError.

tracks = [
    {"track_id": 55, "title": "Dancing Queen"},
    {"track_id": 56, "title": "Take On Me"},
]
plays = [
    {"play_id": 101, "track_id": 55},
    {"play_id": 102, "track_id": 56},
    {"play_id": 104, "track_id": 99},
]
index = {}
for track in tracks:
    index[track["track_id"]] = track
joined = []
for play in plays:
    track = index.get(play["track_id"])
    if track is None:
        print("no track for play", play["play_id"])
        continue
    joined.append({"play_id": play["play_id"], "title": track["title"]})
print(joined)
no track for play 104
[{'play_id': 101, 'title': 'Dancing Queen'}, {'play_id': 102, 'title': 'Take On Me'}]

The index costs a pass over the tracks plus a lookup per play, so the work grows with the sum of the 2 list lengths instead of their product. On that daily load, the gap looks like this:

Unmatched plays: inner or left

Play 104 points at track 99, which the catalog lacks, and the animation's continue dropped it. That is an inner join: only rows with a match on both sides survive. A left join keeps every play and fills the missing fields with None, so the output has exactly as many rows as plays. Choose by what a missing match means: a chart of plays per title can drop it, but a count of total plays must keep it.

tracks = [
    {"track_id": 55, "title": "Dancing Queen"},
    {"track_id": 56, "title": "Take On Me"},
]
plays = [
    {"play_id": 101, "track_id": 55},
    {"play_id": 104, "track_id": 99},
]
index = {}
for track in tracks:
    index[track["track_id"]] = track
for play in plays:
    track = index.get(play["track_id"])
    title = track["title"] if track is not None else None
    print(play["play_id"], title)

Output:

101 Dancing Queen
104 None

When the key repeats on the indexed side

The index holds a single value per key. If the catalog lists track 58 twice, say as the studio recording and as a live version, the second assignment replaces the first, and every play of 58 gets the live title. A nested-loop join would instead have produced 2 rows for each of those plays. Before trusting an index, compare len(index) with len(tracks): if they differ, that side repeats keys, and you either store a list of records per key or fix the catalog first.

The catalog lists track 58 twice. What does the program print?

tracks = [
    {"track_id": 58, "title": "Africa"},
    {"track_id": 58, "title": "Africa (Live)"},
]
index = {}
for track in tracks:
    index[track["track_id"]] = track
plays = [{"play_id": 105, "track_id": 58}]
for play in plays:
    print(play["play_id"], index[play["track_id"]]["title"])
print(len(index), len(tracks))

Which list becomes the index decides what the join can do. Index the side whose key appears once per record and loop over the side whose rows you want in the output. Here that means indexing the catalog and looping over the plays. The loop then visits each play once: an inner join adds a row only when .get returns a record, and a left join adds a row every time, writing None into the fields the missing record would have filled. Reversing the roles, indexing plays by track_id, would keep only the last play of each track.

About this lesson

This section is part of the Data Structures: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.