IntermediateDeduplication

Keep the latest record per id

Task

A CDC feed sends several versions of the same customer. Each record is a dict with id, email and updated_at (an ISO date string such as "2026-02-10"). Write dedupe_latest(records) that keeps only the version with the latest updated_at for each id and returns them sorted by id. The input is in no particular order.

Python 3.14 running in your browser (Pyodide). Standard library only. print() output is shown below the results.

Tests
CallExpected
dedupe_latest([{'id': 2, 'email': 'ben@new.com', 'updated_at': '2026-03-01'}, {'id': 1, 'email': 'asha@a.com', 'updated_at': '2026-01-05'}, {'id': 2, 'email': 'ben@old.com', 'updated_at': '2026-01-20'}])[{'id': 1, 'email': 'asha@a.com', 'updated_at': '2026-01-05'}, {'id': 2, 'email': 'ben@new.com', 'updated_at': '2026-03-01'}]
dedupe_latest([{'id': 3, 'email': 'c@3.com', 'updated_at': '2026-02-14'}, {'id': 3, 'email': 'c@1.com', 'updated_at': '2026-01-02'}, {'id': 3, 'email': 'c@2.com', 'updated_at': '2026-03-01'}])[{'id': 3, 'email': 'c@2.com', 'updated_at': '2026-03-01'}]
dedupe_latest([])[]
Show solution
Python
def dedupe_latest(records):
    latest = {}
    for r in records:
        cur = latest.get(r['id'])
        if cur is None or r['updated_at'] > cur['updated_at']:
            latest[r['id']] = r
    return [latest[k] for k in sorted(latest)]

A dict keyed by id keeps one record per key; the comparison decides which. "Last one wins" only works when the feed is sorted, which CDC feeds often are not after retries and replays.

Revise in the Python for Data Engineers guide, or test yourself with the Python practice sets.