
Code
Side Quest: One Record per ID
Real data repeats itself. A form gets submitted twice, or a file gets imported again. Before you remove duplicates, decide (and write down) a policy:
- What makes two records "the same"? Here: the same
id, after stripping spaces. - Which copy wins? Keep-first trusts the earliest record; keep-last trusts the newest.
- What order comes out? A stable result keeps the records in their original order.
Keep-first with a set
seen = set()
unique = []
for rec in records:
key = rec["id"].strip()
if key in seen:
continue # a later copy: drop it
seen.add(key)
unique.append(rec)
Checking key in seen is fast for a set, so this stays quick even
for huge files.
Watch out: a dict keeps the LAST value
by_id = {r["id"].strip(): r for r in records}
This looks like a neat dedupe, but every later record overwrites the earlier one. The key keeps its first position, but the value is the last copy. That's keep-last in disguise. It's fine if keep-last is your policy, but it should be a choice, not an accident.
Assignment
dedupe(records): return a new list with one record per id (ids compared after.strip()). Keep the first record for each id, in the original order. Don't changerecords.duplicate_counts(records): return a dict mapping each stripped id that appears more than once to the number of extra copies that were dropped, e.g.{"A7": 1, "B2": 1}. Leave out ids with no duplicates.
dedupe(records): return a new list with one record per id (ids compared after.strip()). Keep the first record for each id, in the original order. Don't changerecords.duplicate_counts(records): return a dict mapping each stripped id that appears more than once to the number of extra copies that were dropped, e.g.{"A7": 1, "B2": 1}. Leave out ids with no duplicates.
main.py Python sleeping
Press Run to try your code, then Check to test it.