39. Keep the Latest Record per Key
Difficulty: Medium · Topic: Data wrangling
A change feed delivers several versions of each record, not in order. Write latest(records, key='id', ts='updated_at'): keep, for each value of key, the record with the greatest ts.
- If two versions of a key have the same
ts, keep the one that appears later in the input. - Skip records whose
tsis missing orNone. - Return the kept records sorted by
key.
Your code runs in CPython on our servers against 5 tests, including hidden ones.
Sample test
rows = [
{'id': 2, 'status': 'new', 'updated_at': 1},
{'id': 1, 'status': 'paid', 'updated_at': 5},
{'id': 1, 'status': 'new', 'updated_at': 3},
{'id': 2, 'status': 'paid', 'updated_at': 4},
]
latest(rows)Expected: [{'id': 1, 'status': 'paid', 'updated_at': 5}, {'id': 2, 'status': 'paid', 'updated_at': 4}]
Hints
Hint 1
One pass with a dict from key to the best record so far: O(n).Hint 2
Replace when the new timestamp is greater or equal: that keeps the later of two ties.Hint 3
record.get(ts) returns None for a missing field.Learn the concepts
- Wrangling data without pandas · 5 min read. Parse, flatten, deduplicate, join and aggregate in plain Python, with SQL's null rules.
More Python problems
- Parse Log Lines into Records · Easy
- Reformat Date Strings · Easy
- CSV Rows to Typed Records · Easy
- Flatten Nested JSON · Medium
- Group and Aggregate without pandas · Medium
- Left Join Two Lists of Dicts · Medium
- Merge Overlapping Sessions · Hard
- Schema Validation with a Dead-Letter Queue · Hard