DEV Community

Habib Benabdeslam
Habib Benabdeslam

Posted on

Deduplicate email lists in Python: Gmail dots, plus tags and aliases

Let's say your newsletter subscriber list has Jane.Doe@Gmail.com, janedoe+newsletter@gmail.com and jane.doe@googlemail.com. Lowercasing and trimming will not merge them, but all three deliver to the same inbox. This post will help you build a small function that turns an email into a canonical key you can deduplicate on, and explain where to stop.

The rules that actually hold

Rule Applies to Safe everywhere?
Case does not matter, whitespace is noise All addresses (in practice) Yes
Everything after + in the local part is a tag Gmail, Outlook/Hotmail, iCloud, Fastmail, Proton and others No, only on providers that support it
Dots in the local part are ignored Gmail only No, jane.doe@acme.com and janedoe@acme.com can be two people
googlemail.com is the same as gmail.com Gmail Gmail only

The last two columns are the point: company domains can route jane.doe and janedoe to different people, so only apply provider rules to providers you know in and out.

The function

GMAIL = {"gmail.com", "googlemail.com"}
PLUS_TAGS = GMAIL | {"outlook.com", "hotmail.com", "live.com",
                     "icloud.com", "fastmail.com", "proton.me", "protonmail.com"}

def canonical_email(raw):
    email = raw.strip().lower()
    if email.count("@") != 1:
        return None
    local, domain = email.split("@")
    if domain in PLUS_TAGS:
        local = local.split("+", 1)[0]
    if domain in GMAIL:
        local = local.replace(".", "")
        domain = "gmail.com"
    return f"{local}@{domain}"
Enter fullscreen mode Exit fullscreen mode

Output on a messy sample (from running the code):

Input Canonical key
Jane.Doe@Gmail.com janedoe@gmail.com
janedoe+newsletter@gmail.com janedoe@gmail.com
jane.doe@googlemail.com (trailing space) janedoe@gmail.com
jane.doe@acme.com jane.doe@acme.com
Jane.Doe@ACME.com jane.doe@acme.com
jane.doe+crm@acme.com jane.doe+crm@acme.com (company domain, left alone)
not-an-email None

Deduplicate a CSV, keeping the first row

import csv

def dedupe(src, dst, column="email"):
    seen, kept, dropped = set(), [], 0
    with open(src, newline="", encoding="utf-8") as f:
        rows = list(csv.DictReader(f))
    for row in rows:
        key = canonical_email(row[column])
        if key is None or key in seen:
            dropped += 1
            continue
        seen.add(key)
        kept.append(row)
    with open(dst, "w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
        w.writeheader()
        w.writerows(kept)
    print(f"kept {len(kept)}, dropped {dropped}")
Enter fullscreen mode Exit fullscreen mode

Keep the original address in the output. The canonical key is for matching only; sending to janedoe@gmail.com when someone signed up as jane.doe+news@gmail.com breaks their inbox filters.

When "keep the first row" is not enough

Duplicates often carry different data: one row has the phone number, another has the job title. Instead of dropping rows, group them by key and merge the fields, for example keeping the most recent non-empty value per column. That is where a hand-written script starts to grow, and where a tool with merge rules saves time.

Datablist does email deduplication with these normalization rules and field-by-field merging on CSV files completely for free: datablist.com/learn/data-cleaning/email-deduplication.

Top comments (0)