Combining Structures for One Task

Concepts covered: Collections

Each structure answers some questions at once and others slowly or not at all. A list keeps order and allows repeats but finds an item only by scanning. A set answers membership with a single lookup but keeps no order. A dict finds a value by key and keeps its keys in insertion order. Some tasks need 2 of those answers at the same time, and the fix is to keep 2 structures that describe the same data.

Questionlistsetdict
What comes next, in order?front of the listno order keptfirst key inserted
Is X already here?scans every itema single lookupa single lookup, by key
What is stored under key K?scans every itemstores no valuesa single lookup
Can an entry repeat?yesnokeys no, values yes

A play queue: list plus set

A listening queue plays tracks in the order they were added and refuses a track that is already waiting. The list supplies the order. Testing track_id in queue on a list scans it from the front, so a set of queued ids sits beside it to answer that test with a single lookup. The price is a rule: every change touches both structures, inside the same function.

queue = []
queued = set()

def enqueue(track_id):
    if track_id in queued:
        print("already queued:", track_id)
        return
    queue.append(track_id)
    queued.add(track_id)

def play_next():
    track_id = queue.pop(0)
    queued.remove(track_id)
    return track_id

enqueue(55)
enqueue(56)
enqueue(55)
print(play_next())
enqueue(55)
print(queue)

Output:

already queued: 55
55
[56, 55]

Once 55 plays, it leaves both the list and the set, so adding it again succeeds and it joins the back of the queue.

Tracing every call shows the 2 structures moving in step: after each call, the set holds exactly the ids waiting in the list.

CallqueuequeuedPrints
enqueue(55)[55]{55}nothing
enqueue(56)[55, 56]{55, 56}nothing
enqueue(55)[55, 56]{55, 56}already queued: 55
play_next()[56]{56}55
enqueue(55)[56, 55]{55, 56}nothing

Grouping: a dict of lists

Pairing can also mean nesting. Grouping plays by listener needs lookup by user, which a dict gives, and each user's plays in order with repeats kept, which a list gives. The dict maps each user_id to a list of its own, created the first time that user appears.

plays = [
    {"user_id": 7, "track_id": 55},
    {"user_id": 8, "track_id": 56},
    {"user_id": 7, "track_id": 57},
    {"user_id": 7, "track_id": 55},
]
by_user = {}
for play in plays:
    user_id = play["user_id"]
    if user_id not in by_user:
        by_user[user_id] = []
    by_user[user_id].append(play["track_id"])
print(by_user)

Output:

{7: [55, 57, 55], 8: [56]}

Swap the inner list for a set and each user keeps distinct tracks but loses play order. Keep a list and a set for each user, and the queue pattern from above runs inside every key of by_user.

A job reads status updates for orders. It must answer "what is the latest status of order X?" and print orders in the order each first showed up. What does it need?

Capstone: from raw events to clean rows

Unique plays flow left to right; the catalog enters only at the join.
  • Raw events (source, nested dicts)
  • Dedupe (transform, set + list)
  • Tracks (source, catalog list)
  • Join (transform, dict index)
  • Group (transform, dict of lists)
  • Recap (consumer, titles per user)
  • Raw events -> Dedupe
  • Dedupe -> Join
  • Tracks -> Join
  • Join -> Group
  • Group -> Recap

The last practice runs the lesson's steps on a handful of events: drop the repeats, attach titles through an index, and group by listener.

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.