Remove duplicate CSV rows in Python, keeping the latest record
By StringClass · Published
Read the CSV with csv.DictReader, keep a dictionary keyed by record ID, and replace a stored row only when the new timestamp is later. Define timestamp ties and output ordering before writing the code.
Before you start: You know Python functions, loops, lists, and dictionaries. The example uses only the standard library and synthetic data.
Download the sample CSV (synthetic customer records).
Try the Python example
Edit the synthetic CSV or the function, then run it to see the selected records. Try changing a timestamp or adding a tied version. Use sample data; this page does not save your edits.
Use Tab to move between controls. Code runs in an isolated browser workspace. Edits stay on this page until you leave or reset it.
Ready to run
Run the example to see its output here.
Define duplicate and latest
Suppose a customer export contains several versions of each record. You need one row per customer_id, keeping the version with the newest updated_at timestamp. Comparing whole rows or removing repeated names solves a different problem: two customers can share a name, and an update can change every field except its identifier.
Our rules are explicit:
- IDs are case-sensitive text. Surrounding whitespace is removed, but leading zeros are preserved. Blank IDs are errors.
- Timestamps must be valid UTC values in
YYYY-MM-DDTHH:MM:SSZformat. A malformed value stops processing rather than being guessed. - The newest timestamp wins even if the input is not sorted. When timestamps tie, the first row wins.
- Output follows the order in which each ID first appeared. Selecting a later version does not move its ID.
These are example business rules, not universal CSV rules. Decide them with the owner of your data before deleting records.
Sample CSV
Save this as customers.csv, or use the sample download above. The names and records are synthetic.
customer_id,name,updated_at
C-02,"River, Sam",2026-10-20T09:00:00Z
C-01,Ada,2026-10-21T12:00:00Z
C-02,"River, Samuel",2026-10-22T08:00:00Z
C-01,Ada old,2026-10-19T12:00:00Z
C-03,Bo,2026-10-21T10:00:00Z
C-02,Sam tie,2026-10-22T08:00:00Z
The newest C-02 row contains a comma inside a quoted name. Splitting each line on commas would break that field. Python's csv module understands the quoting rules and gives us dictionaries keyed by the header names.
Complete Python example
The function accepts CSV text and returns fresh dictionaries. It leaves the original text unchanged and does not need pandas.
import csv
from datetime import datetime, timezone
from io import StringIO
def latest_customers(csv_text):
reader = csv.DictReader(StringIO(csv_text, newline=""))
required = ["customer_id", "name", "updated_at"]
if reader.fieldnames != required:
raise ValueError("Expected header: customer_id,name,updated_at")
latest = {}
for record_number, row in enumerate(reader, start=1):
if None in row or any(value is None for value in row.values()):
raise ValueError(f"Record {record_number}: wrong number of fields")
customer_id = row["customer_id"].strip()
if not customer_id:
raise ValueError(f"Record {record_number}: blank customer_id")
try:
updated = datetime.strptime(
row["updated_at"], "%Y-%m-%dT%H:%M:%SZ"
).replace(tzinfo=timezone.utc)
if updated.isoformat(timespec="seconds").replace("+00:00", "Z") != row["updated_at"]:
raise ValueError("Non-canonical timestamp")
except ValueError as error:
raise ValueError(
f"Record {record_number}: invalid UTC timestamp"
) from error
previous = latest.get(customer_id)
if previous is None or updated > previous[0]:
latest[customer_id] = (updated, dict(row, customer_id=customer_id))
return [row for updated, row in latest.values()]
with open("customers.csv", encoding="utf-8-sig", newline="") as source:
rows = latest_customers(source.read())
with open("customers-latest.csv", "w", encoding="utf-8", newline="") as target:
writer = csv.DictWriter(
target, fieldnames=["customer_id", "name", "updated_at"]
)
writer.writeheader()
writer.writerows(rows)
Run this with Python 3.10 or later in the directory containing customers.csv. It creates a separate output file; keep the original for review. utf-8-sig accepts a UTF-8 byte order mark if the export contains one. newline="" lets the CSV module handle record endings correctly.
Expected output, shown with normalized line endings:
customer_id,name,updated_at
C-02,"River, Samuel",2026-10-22T08:00:00Z
C-01,Ada,2026-10-21T12:00:00Z
C-03,Bo,2026-10-21T10:00:00Z
How the dictionary works
The dictionary maps each ID to its best timestamp and row so far. C-02's later version replaces its earlier value. C-01's older version is ignored. C-02's timestamp tie is also ignored because the comparison is strictly >, not >=.
Python dictionaries preserve insertion order. Replacing a value for an existing key does not move the key, which gives us the promised output order. If you need rows sorted by ID instead, make that a separate, explicit sorting step.
At fixed field widths, processing takes O(n) expected time and O(k) retained record space for n input rows and k distinct IDs. This complete example also reads the input text into memory and constructs an output list. Very large exports need a streaming input design or a database; a dictionary alone does not make the whole program constant-memory.
Mistakes and boundary checks
- A set of whole rows removes exact repeats, but does not select the newest version of an ID.
- Keeping the last row seen fails when an old update appears later in the file.
- Comparing differently formatted timestamp strings can choose the wrong record. Parse the documented format first.
- A header-only CSV returns an empty list. An empty file has no required header and raises an error.
- Missing fields, extra fields, blank IDs, and invalid dates raise errors. Empty names are allowed by this contract.
- Stripping an ID is deliberate here. Do not lowercase identifiers or collapse meaningful spaces without a requirement.
Try it yourself
Add a row with ID C-01 and timestamp 2026-10-23T12:00:00Z. Its data should replace Ada's record, but C-01 should remain second in the output. Then add a row with the same timestamp: under our tie rule, the existing winner remains.
As an extension, change the function to report how many versions were discarded for each ID. Keep this diagnostic separate from the returned customer rows so the output schema stays predictable.
Reference: Python's csv documentation covers dictionary readers, writers, quoting, and newline handling.