Deduplicating Rows by a Composite Key

MLOpsEasy+10 XP+10

Deduplicating Rows by a Composite Key

Pipelines deliver duplicates. A retry re-sends a batch, two upstream systems both report the same event, a backfill overlaps a live load. Left alone, those copies quietly reweight your training data — the duplicated rows count twice, and the model leans toward them.

Task: write deduplicate(rows, keys) returning the rows with duplicates removed.

  • rows is a list of dictionaries. keys lists the field names that together identify a record.
  • Two rows are duplicates when they agree on every field in keys. The other fields are irrelevant to the comparison, however different they are.
  • Keep the first occurrence of each identity and drop the later ones.
  • Preserve the original order of the rows you keep.
  • Return the row dictionaries themselves, unchanged.

"Keep the first" is a real decision and worth being deliberate about. With rows arriving oldest-first it keeps the original and discards corrections; keep the last instead and you treat later arrivals as updates. Either can be right — what's never right is leaving it unspecified, because then your pipeline's output depends on batch ordering nobody controls.

Build each row's identity as a tuple of its key values and track the ones you've seen in a set. Tuples are hashable where dictionaries and lists are not, which is precisely why this is the standard shape for a composite key.

Examples

rows = [{'id': 1, 'v': 'a'}, {'id': 1, 'v': 'b'}, {'id': 2, 'v': 'c'}]
keys = ['id']
returns [{'id': 1, 'v': 'a'}, {'id': 2, 'v': 'c'}]
rows = [{'a': 1, 'b': 1}, {'a': 1, 'b': 2}]
keys = ['a', 'b']
returns [{'a': 1, 'b': 1}, {'a': 1, 'b': 2}]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run