Disclosure: This tutorial was written with AI assistance. I work with ExtractHelp, a data services agency. All sample data below is fictional.

The problem

You have two CSV files. One holds orders, the other holds customers. Both share a customer_id column, and you want one combined file.

A quick merge can hide two problems. Rows whose key has no match can disappear silently. Duplicate keys in the second file can multiply rows or overwrite each other. This tutorial joins the files on the shared key, keeps every left row, and reports unmatched and duplicate keys instead of hiding them.

The sample files

orders.csv:

order_id,customer_id,total 1001,C-01,49.00 1002,C-02,120.50 1003,C-99,15.00 

customers.csv:

customer_id,name,city C-01,Ana Example,Leeds C-02,Ben Sample,York C-02,Ben Sample,York C-03,Cara Demo,Hull 

Notice the traps: order 1003 points to C-99, which has no customer. Customer C-02 appears twice. Customer C-03 has no orders.

Step 1: Read both files

Use Python's built-in csv module. It needs no extra installs and handles quoted fields correctly.

import csv from collections import Counter def read_csv(path): with open(path, newline="", encoding="utf-8") as f: return list(csv.DictReader(f)) orders = read_csv("orders.csv") customers = read_csv("customers.csv") key = "customer_id" 

Step 2: Check for duplicate keys first

Before joining, count how often each key appears in the lookup file. A duplicate key means the join result depends on which row you happen to pick, so report it.

right_counts = Counter(row[key] for row in customers) duplicate_keys = sorted(k for k, c in right_counts.items() if c > 1) 

Step 3: Build the lookup and join

Build a dictionary from the customers file, then walk the orders. Keep every order row. When there is no match, leave the joined fields empty and record the key.

right_by_key = {} for row in customers: right_by_key.setdefault(row[key], row) joined = [] unmatched_left = [] for row in orders: match = right_by_key.get(row[key]) if match is None: unmatched_left.append(row[key]) joined.append({**row, "name": "", "city": ""}) else: joined.append({**row, "name": match["name"], "city": match["city"]}) 

Step 4: Report what did not match

Also report keys that exist only in the lookup file. Then write the joined file. Your originals stay untouched; you write a new file.

left_keys = {row[key] for row in orders} unmatched_right = sorted(set(right_by_key) - left_keys) with open("joined.csv", "w", newline="", encoding="utf-8") as f: writer = csv.DictWriter(f, fieldnames=["order_id", "customer_id", "total", "name", "city"]) writer.writeheader() writer.writerows(joined) print("unmatched left keys:", unmatched_left) print("unmatched right keys:", unmatched_right) print("duplicate right keys:", duplicate_keys) 

Running this on the sample data prints:

unmatched left keys: ['C-99'] unmatched right keys: ['C-03'] duplicate right keys: ['C-02'] 

The joined file keeps all three orders. Order 1003 has empty name and city fields, which is honest: there is no customer C-99 to join.

Common mistakes

  • Using an inner join by default. It drops unmatched rows without telling you, so totals quietly change.
  • Ignoring duplicate keys. With pandas, a duplicated lookup key multiplies rows; with a dictionary, one row silently wins. Either way, check first.
  • Joining on keys with different formats. C-01 and c-01 will not match. Agree the key format before you join, and trim stray spaces.
  • Overwriting an original file. Write the result to a new file so you can compare and re-run.
  • Skipping the report. The unmatched lists are the most valuable output. They tell you exactly which records need attention.

Conclusion

A safe CSV join has three habits: check for duplicate keys, keep unmatched rows visible, and report both sides that did not match. The code above does all three with the standard library.

If your files need this kind of care at scale, with merge rules agreed in advance and a log of every change, that is the work described in ExtractHelp's data cleaning service.