Removing Duplicate Records

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

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.

plays = [
    {"play_id": 101, "track_id": 55},
    {"play_id": 101, "track_id": 55},
]
unique = set(plays)
print(unique)

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"])
        continue
    seen.add(play["play_id"])
    unique.append(play)
for play in unique:
    print(play["play_id"], play["track_id"])
skip copy of 101
101 55
102 56
103 55

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

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.

a = {"play_id": 101, "track_id": 55}
b = {"track_id": 55, "play_id": 101}
print(a == b)
print(tuple(a.items()) == tuple(b.items()))
print(tuple(sorted(a.items())) == tuple(sorted(b.items())))

Output:

True
False
True

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.

plays = [
    {"user_id": 7, "track_id": 55},
    {"track_id": 56, "user_id": 8},
    {"track_id": 55, "user_id": 7},
]
seen = set()
unique = []
for play in plays:
    fingerprint = tuple(sorted(play.items()))
    if fingerprint in seen:
        continue
    seen.add(fingerprint)
    unique.append(play)
print(len(unique))
for play in unique:
    print(play)

Output:

2
{'user_id': 7, 'track_id': 55}
{'track_id': 56, 'user_id': 8}

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?

events = [
    {"play_id": 101, "status": "started"},
    {"play_id": 102, "status": "started"},
    {"play_id": 101, "status": "finished"},
]
latest = {}
for event in events:
    latest[event["play_id"]] = event
for event in latest.values():
    print(event["play_id"], event["status"])

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.

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.