Detect Duplicate Keys in a CSV File Using Python Standard Library

Detect Duplicate Keys in a CSV File Using Python Standard Library EduTechBuddy.com © edutechbuddy.com
Detect Duplicate Keys in a CSV File Using Python Standard Library © edutechbuddy.com
Learn how to identify duplicate entries in any CSV column using a concise Python script that relies only on the standard library. This approach helps prevent data import errors and accidental overwrites in platforms like Shopify or contact lists.

Duplicate keys in CSV files often trip up data imports or quietly overwrite records. When two rows in a Shopify export share the same Handle, or a contact list includes both Anna@x.de and anna@x.de, importers may throw errors or silently replace data.

Why Duplicate Keys Matter

Platforms typically require unique values in certain columns, such as product handles or email addresses. If a value repeats, the import might fail or overwrite records without notice. Spotting these duplicates before importing protects data integrity and avoids accidental loss or corruption.

Checking for duplicates is a basic data-quality step, but not every repeat signals a problem. Sometimes, a key repeats for categories or households, while primary identifiers or record IDs must stay unique. U.S. federal records-management rules require agencies to assign unique identifiers and keep metadata consistent across storage, so duplicate checks should match the uniqueness rules of the target system. The federal records framework also names CSV as a transfer format for administrative and technical metadata, and mandates unique record IDs for permanent records, making uniqueness and consistency regulatory requirements (Electronic Code of Federal Regulations, 36 CFR Part 1236).

Python Script for Finding Duplicates

A short Python script using only the standard library can scan a CSV for duplicate values in any column you specify. This method skips pandas and other dependencies, so it stays lightweight and works in many environments.

import csv, sys
from collections import defaultdict

def find_duplicates(path, key):
    seen = defaultdict(list)
    with open(path, newline="", encoding="utf-8-sig") as f:
        for line_no, row in enumerate(csv.DictReader(f), start=2):
            value = (row.get(key) or "").strip().lower()
            if value:
                seen[value].append(line_no)
    return {k: v for k, v in seen.items() if len(v) > 1}

if __name__ == "__main__":
    path, key = sys.argv[1], sys.argv[2]
    dupes = find_duplicates(path, key)
    for value, lines in sorted(dupes.items()):
        print(f"{value}: lines {', '.join(map(str, lines))}")
    print(f"{len(dupes)} duplicate value(s) found")
    sys.exit(1 if dupes else 0)

How to Use the Script

Save the script as dupes.py and run it from the command line, giving the CSV file and the column name to check. For example:

python dupes.py products.csv Handle

The script lists each duplicate value and the line numbers where it appears. For a file with these rows:

Handle,Title
mug-red,Red Mug
Mug-Red ,Red Mug 2
tee-blue,Blue Tee
TEE-BLUE,Tee
hat,Hat

The output will be:

mug-red: lines 2, 3
tee-blue: lines 4, 5
2 duplicate value(s) found

Key Implementation Details

  • UTF-8-SIG Encoding: The script uses utf-8-sig to handle the byte order mark that Excel sometimes adds. This ensures the first column name matches as expected, following Python's CSV documentation for files with a UTF-8 byte-order mark.
  • Case and Whitespace Handling: Using strip().lower() on each value means duplicates that differ only by case or extra spaces are caught. This normalization can reveal hidden duplicates, but identifier comparison rules differ by system, so normalization should be chosen carefully. For case-sensitive matching, remove .lower() from the script.
  • Line Numbering: Line numbers start at 2 because the first line is the header, matching what spreadsheet editors show. The script records every nonblank normalized key and the CSV line number where it appears, so the first data row is line 2.
  • Exit Code: The script exits with code 1 if it finds duplicates, which lets you use it in shell scripts or CI pipelines as a pre-import check. The returned dictionary includes only keys with more than one line, so unique values are left out. An exit status of 0 means no duplicates were found, while 1 signals at least one duplicate value was detected.

Practical Tips for CSV Data Management

This script only reports duplicate values and does not change your CSV file. Review the output and decide which rows to keep or edit before importing. This is especially useful for Shopify product data or contact lists where unique keys are required.

In regulated or scientific settings, CSV quality checks often combine automated and manual review. For example, the U.S. Food and Drug Administration's WearGait-PD dataset went through a quality control process with both automatic and manual checks for missing columns, invalid variable types, and other integrity issues, with problems reassigned to a second researcher for correction and revalidation (FDA WearGait-PD Dataset Technical Description). For duplicate-key workflows, this supports using the Python script as an early screening step, followed by header validation, missing-value review, schema checks, and confirmation against the receiving platform's import rules.

Some data schemas require uniqueness across a combination of columns, not just one field. The U.S. Bureau of Labor Statistics' Consumer Expenditure Survey, for example, defines records as unique by the combination of NEWID and SEQNO on the MTBI file, showing the need for composite key support in robust CSV validators (BLS CE Data Quality Profile Reference Guide).

The supplied implementation works for batch validation because it prints each duplicated normalized value with all affected line numbers and returns a nonzero process status when duplicates exist. However, it does not check that the requested column exists, distinguish blank keys from invalid keys, or keep the original spelling and capitalization in its report after normalization. It also treats values such as Anna@x.de and anna@x.de as the same key, which may fit email validation but not case-sensitive identifiers. For production, document the comparison policy, fail clearly on missing headers, and keep original values alongside normalized ones for auditability, as recommended by the Python Software Foundation documentation.

Building small, focused tools like this helps automate data validation and cut manual errors in programming workflows.

Camila Ferreira Editor EduTechBuddy.com
Co-Founder

Camila Ferreira

Camila Ferreira is the Co-Founder of EduTechBuddy, where her editorial focus is programming education and practical software development skills. Her primary subjects include Python programming, Git version control, and the fundamental concepts beginners need to understand when working with code.