Data Structures: Intermediate
Prefix each inner key with its parent
Walk the top-level pairs. When a value is a dict, which isinstance(value, dict) checks, copy each of its pairs out under the name parent_inner; otherwise copy the pair unchanged. The prefix keeps the listener's id and the track's id apart. Without it, both would land in a single column called id, and the second would overwrite the first.
| play_id | user_id | user_country | track_id | track_title | ms_played |
|---|---|---|---|---|---|
| 101 | 7 | SE | 55 | Dancing Queen | 183000 |
Columns come out in the record's own key order. Dicts keep insertion order and the loop follows it, so user_id takes the place user held in the original, with user_country right behind it.
Deeper nesting takes another pass
flatten_once lifts exactly 1 level. Give the track an album, and the first pass produces a column track_album whose value is still a dict. Feeding that output back into flatten_once lifts the album's fields to track_album_title and track_album_year. Each level of nesting costs a further pass.
What flattening loses
Colliding names
Suppose a record carries a top-level user_id and also a user dict with an id. Both produce the column user_id. Assigning to a key that already exists replaces its value, so whichever pair the loop reaches second wins, and the earlier value vanishes.
This record holds both a top-level user_id and a nested user dict. What does the program print?
Lists inside a record
A list such as "tags": ["pop", "70s", "disco"] has no single cell to go in. The usual answer is to explode it: produce 1 row per list item and copy the parent's fields onto every row. Each tag becomes queryable, and the parent's values get multiplied: a play with 3 tags becomes 3 rows, and every one of them claims 183000 milliseconds played.
ms_played from the original records, or keep exploded tags in a table of their own that carries play_id, so the play rows stay 1 per play.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.
| play_id | track_id |
|---|---|
| 101 | 55 |
| 102 | 56 |
| 103 | 55 |
| 104 | 99 |
| track_id | title |
|---|---|
| 55 | Dancing Queen |
| 56 | Take On Me |
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.
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"]] = trackjoined = []for play in plays:track = index.get(play["track_id"])if track is None:print("no track for play", play["play_id"])continuejoined.append({"play_id": play["play_id"], "title": track["title"]})print(joined)
Build the index from tracks once, then look up each play; play 104 finds nothing.
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.
| play_id | title |
|---|---|
| 101 | Dancing Queen |
| 102 | Take On Me |
| 103 | Dancing Queen |
| play_id | title |
|---|---|
| 101 | Dancing Queen |
| 102 | Take On Me |
| 103 | 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?
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.
The joins above matched records 1 at a time. Other questions are about whole collections. Which tracks entered the catalog since yesterday, and which left it? Which fields does one event carry that another lacks? When records sit in dicts keyed by id, those are questions about keys, and keys can be compared with | and &, the set operators you already know, along with - and ^.
d.keys() returns a view that behaves like a set. It supports those 4 operators against another keys view or a plain set, and each result is a new, ordinary set, with no conversion step and no loop. The values view does not, because values can repeat and need not be hashable.
Diffing 2 snapshots of a catalog
| Expression | Holds | Here |
|---|---|---|
| today.keys() - yesterday.keys() | keys only in today: added | {58} |
| yesterday.keys() - today.keys() | keys only in yesterday: removed | {56} |
| today.keys() & yesterday.keys() | keys in both: kept | {55, 57} |
| today.keys() ^ yesterday.keys() | keys on exactly 1 side | {56, 58} |
| today.keys() | yesterday.keys() | every key either snapshot has | {55, 56, 57, 58} |
Key math says which ids exist, never what they hold. Track 57 sits in both snapshots, yet its title changed from Heroes to Heroes (Remaster). Finding that takes the last loop in the program: walk the shared keys and compare values. A change feed emits those 3 results. A downstream table inserts the added ids and deletes the removed ones, then updates the rows whose values changed.
sorted() before printing or comparing them, so the same input always gives the same lines. Every set printed in this section goes through sorted() for that reason.Comparing the fields of 2 records
The same operators work on the field names of single records. Check 2 events that should share a schema with ^: anything in the result exists on only 1 side, which usually means a field was renamed or dropped upstream. A set of required fields minus a record's keys names exactly what that record is missing, and issubset answers yes or no.
Flattened rows bound for a single table need the union of everyone's columns. Start from an empty set, union in each row's keys, then sort the result into a fixed column list. A row missing a column gets None through .get.
The union loop grows columns row by row: after the first row it holds play_id and track_id, and the second row adds ms_played. Sorting turns the set into a list with a fixed order, so the column list is the same on every run, and building each row's values by walking that list puts every value under the same column in every row. row.get(column) returns None for the 2 cells the rows lack.
What does this program print?
For 3 of the operators, the answer is the same whichever dict comes first: a.keys() & b.keys() holds the same keys as b.keys() & a.keys(), and the same goes for | and ^. Subtraction is the exception. a.keys() - b.keys() keeps the keys of a that b lacks, so swapping the operands swaps the question. For 2 snapshots, newer minus older names what was added and older minus newer names what was removed; written the wrong way round, every addition is reported as a removal.
For strings or numbers, set(values) removes repeats. For dicts it fails at once: a set stores only hashable values, and a dict is mutable, so Python gives it no hash.
Running it stops at line 5 with TypeError: unhashable type: 'dict', and nothing prints. Building a set means hashing every element, and the first dict already has no hash. A set would lose something even if it accepted dicts: the order the records arrived in. Downstream steps, such as building a listener's play history, expect rows in arrival order, and a set hands its elements back in an order of its own that has nothing to do with arrival.
A seen set beside an output list
Split the job between 2 structures. A set holds the ids already kept, so "have I met this record?" becomes a single membership test. A list collects the records to keep, appended as the loop reaches them. The set stores ints, which are hashable; the list stores the dicts, which do not need to be.
plays = [{"play_id": 101, "track_id": 55},{"play_id": 102, "track_id": 56},{"play_id": 101, "track_id": 55},{"play_id": 103, "track_id": 55},]seen = set()unique = []for play in plays:if play["play_id"] in seen:print("skip copy of", play["play_id"])continueseen.add(play["play_id"])unique.append(play)for play in unique:print(play["play_id"], play["track_id"])
The set answers whether an id was kept; the list keeps the records in arrival order.
No id? Fingerprint the whole record
Some feeds carry no reliable id, and a duplicate means every field matches. Build a hashable stand-in for the dict: tuple(sorted(record.items())). The tuple holds the (key, value) pairs, and the sort matters, because 2 equal dicts can store their keys in different orders, and their unsorted tuples then differ.
The fingerprint takes the id's place in the seen-set loop. The set now holds tuples of (key, value) pairs, which are hashable because every key is a string and every value an int, and 2 records whose fields arrived in different orders collapse to 1 fingerprint.
- ▸A value that is a list or a dict makes the tuple unhashable, and adding that tuple to the set raises
TypeError. - ▸Flatten nested records before fingerprinting, so every value is a plain scalar like a number or a string.
Nonehashes fine too. - ▸A fingerprint treats 2 copies that differ only in an upload timestamp as different records. Leave such fields out of it, or dedupe by id.
Keeping the last copy instead
Sometimes a later copy is a correction: a play first reported as started and then as finished. To keep the last copy, store each record in a dict under its id, so every repeat replaces the stored value. A dict remembers where a key was first inserted, and replacing its value does not move it.
Events for play 101 arrive twice. What does the program print?
In the seen-set loop, the order of 2 lines matters: test membership first, then add. The test checks whether an earlier record already used this id, so it has to run while the set holds only earlier ids. Add the current id before testing and every record finds itself in the set, the first copy of each included, so the output comes back empty. The keep-last version has no such order to get wrong, because a single assignment to latest[event["play_id"]] does the whole job.
| Question | list | set | dict |
|---|---|---|---|
| What comes next, in order? | front of the list | no order kept | first key inserted |
| Is X already here? | scans every item | a single lookup | a single lookup, by key |
| What is stored under key K? | scans every item | stores no values | a single lookup |
| Can an entry repeat? | yes | no | keys 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.
| Call | queue | queued | Prints |
|---|---|---|---|
| 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.
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.
> A food delivery app sends order events as nested JSON: the customer and the restaurant are dicts inside each order, each order carries a list of items, and a retried request can send the same order twice. The nightly job must load clean order rows, attach each restaurant's name from a separate restaurant list, report which restaurants joined or left since last night, and build each customer's order history.
customer and restaurant into customer_id and restaurant_id columns, and the item list becomes its own exploded table keyed by order id, so order totals are not multiplied.len(index) with the list length first catches a restaurant listed twice.len(index) against the list, then look each record up with .get: an inner join skips a None, a left join keeps it.- and &, along with ^ and |, so snapshot diffs and schema checks become a single expression each; sort the result before printing it.tuple(sorted(record.items())), beside a list that keeps arrival order; a dict keyed by id keeps the last copy instead.Flatten, join, diff and dedupe records with dicts, lists and sets, and know when a task needs 2 of them at once.
- Category
- Python
- Difficulty
- intermediate
- Duration
- 48 minutes
- Challenges
- 21 hands-on challenges
Topics covered: Flattening Nested Records, Joining Records on a Shared Key, Set Math on Dictionary Keys, Removing Duplicate Records, Combining Structures for One Task
Lesson Sections
- Flattening Nested Records (concepts: Nested Dicts)
A table row is a fixed set of named columns, and each cell holds a single value: a number, a string, a timestamp. Event data seldom arrives in that shape. A play event from a music app carries the listener as a dict inside the record, the track as a second dict, and sometimes a list of tags. Before those events can be loaded as rows, every nested value has to move up to the top level under a column name of its own. That step is called flattening. Prefix each inner key with its parent Deeper nest
- Joining Records on a Shared Key (concepts: List Comprehension)
The nested-loop join Build an index once, then look up 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 When the key repeats on the indexed side
- Set Math on Dictionary Keys (concepts: Set Operations)
Diffing 2 snapshots of a catalog Comparing the fields of 2 records
- Removing Duplicate Records (concepts: Sorting)
Event pipelines deliver some records more than once. A phone that loses its connection mid-upload sends the batch again; a job that crashes and restarts reprocesses its last input. Each copy is a separate dict with identical contents, and counting both inflates every total built on top of them. A seen set beside an output list The first copy of 101 is kept and the later copy is skipped, so the output follows first appearance. No id? Fingerprint the whole record Keeping the last copy instead
- Combining Structures for One Task (concepts: 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. A play queue: list plus set Once 55 plays, it leaves both the list and the set, so adding it aga