Flattening Nested Records

Concepts covered: 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.

{
  "play_id": 101,
  "user": {"id": 7, "country": "SE"},
  "track": {"id": 55, "title": "Dancing Queen"},
  "ms_played": 183000
}

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.

def flatten_once(record):
    flat = {}
    for key, value in record.items():
        if isinstance(value, dict):
            for inner_key, inner_value in value.items():
                flat[f"{key}_{inner_key}"] = inner_value
        else:
            flat[key] = value
    return flat

play = {
    "play_id": 101,
    "user": {"id": 7, "country": "SE"},
    "track": {"id": 55, "title": "Dancing Queen"},
    "ms_played": 183000,
}
row = flatten_once(play)
for column, value in row.items():
    print(column, value)

Output:

play_id 101
user_id 7
user_country SE
track_id 55
track_title Dancing Queen
ms_played 183000
play_iduser_iduser_countrytrack_idtrack_titlems_played
1017SE55Dancing Queen183000

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.

def flatten_once(record):
    flat = {}
    for key, value in record.items():
        if isinstance(value, dict):
            for inner_key, inner_value in value.items():
                flat[f"{key}_{inner_key}"] = inner_value
        else:
            flat[key] = value
    return flat

play = {"play_id": 101, "track": {"id": 55, "album": {"title": "Arrival", "year": 1976}}}
once = flatten_once(play)
print(once)
print(flatten_once(once))

Output:

{'play_id': 101, 'track_id': 55, 'track_album': {'title': 'Arrival', 'year': 1976}}
{'play_id': 101, 'track_id': 55, 'track_album_title': 'Arrival', 'track_album_year': 1976}

What flattening loses

Flattening can lose information in 2 ways. Neither raises an error, so both reach the table unnoticed.

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?

play = {"user_id": 9, "user": {"id": 7}}
flat = {}
for key, value in play.items():
    if isinstance(value, dict):
        for inner_key, inner_value in value.items():
            flat[f"{key}_{inner_key}"] = inner_value
    else:
        flat[key] = value
print(flat)

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.

play = {"play_id": 101, "ms_played": 183000, "tags": ["pop", "70s", "disco"]}
rows = []
for tag in play["tags"]:
    row = {"play_id": play["play_id"], "ms_played": play["ms_played"], "tag": tag}
    rows.append(row)
total = 0
for row in rows:
    total += row["ms_played"]
print(len(rows))
print(total)

Output:

3
549000

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.