Set Math on Dictionary Keys

Concepts covered: Set Operations

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

yesterday = {55: "Dancing Queen", 56: "Take On Me", 57: "Heroes"}
today = {55: "Dancing Queen", 57: "Heroes (Remaster)", 58: "Africa"}
added = today.keys() - yesterday.keys()
removed = yesterday.keys() - today.keys()
kept = today.keys() & yesterday.keys()
print(sorted(added))
print(sorted(removed))
print(sorted(kept))
changed = []
for track_id in sorted(kept):
    if today[track_id] != yesterday[track_id]:
        changed.append(track_id)
print(changed)

Output:

[58]
[56]
[55, 57]
[57]
ExpressionHoldsHere
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.

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.

required = {"play_id", "track_id", "ms_played"}
good = {"play_id": 101, "track_id": 55, "ms_played": 183000}
renamed = {"play_id": 102, "track_id": 56, "msPlayed": 95000}
print(sorted(good.keys() ^ renamed.keys()))
print(sorted(required - renamed.keys()))
print(required.issubset(good.keys()))
print(required.issubset(renamed.keys()))

Output:

['msPlayed', 'ms_played']
['ms_played']
True
False

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.

rows = [
    {"play_id": 101, "track_id": 55},
    {"play_id": 102, "ms_played": 95000},
]
columns = set()
for row in rows:
    columns = row.keys() | columns
columns = sorted(columns)
print(columns)
for row in rows:
    values = []
    for column in columns:
        values.append(row.get(column))
    print(values)

Output:

['ms_played', 'play_id', 'track_id']
[None, 101, 55]
[95000, 102, None]

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?

stock_a = {"apple": 3, "pear": 0, "fig": 5}
stock_b = {"pear": 2, "fig": 5, "kiwi": 1}
print(sorted(stock_a.keys() & stock_b.keys()))
print(len(stock_a.keys() | stock_b.keys()))

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.

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.