Tony CantaveHow I Use Python Sets to Reconcile Two Exports in Seconds
By Tony Cantave ·
One of the most common questions I ran into in logistics and manufacturing work was simple to ask and annoying to answer: do these two lists match? The dispatch system says one set of orders went out today. The ERP export says something slightly different. Somebody needs to know which orders are missing, which are extra, and which exist in both but disagree. For years I watched people answer that with two spreadsheets side by side and a lot of scrolling. Now I answer it with a short Python script built around sets.
Why sets fit this problem
A set is an unordered collection with no duplicates, and it is built for membership questions. Checking whether a value is in a set takes roughly the same time whether the set holds ten items or a million, because Python stores set items in a hash table. Checking whether a value is in a list means walking the list item by item. When you compare two exports with tens of thousands of rows each, that difference is the gap between instant and a coffee break.
Sets also come with the exact operations reconciliation needs, as methods:
a = {"A100", "A101", "A102"}
b = {"A101", "A102", "A103"}
print(a.difference(b)) # {'A100'} in a only
print(b.difference(a)) # {'A103'} in b only
print(a.intersection(b)) # {'A101', 'A102'} in both
print(a.symmetric_difference(b)) # {'A100', 'A103'} in exactly onePython also has operator shortcuts for these, but I use the method names in scripts other people will read. They explain themselves.
Step one: load the keys cleanly
Most reconciliation bugs are not set bugs. They are key bugs. An order number with a trailing space, a lowercase letter, or a leading zero dropped by a spreadsheet will look like a missing record when it is not. So I normalize keys as I load them:
import csv
def load(path, key_field):
records = {}
with open(path, newline="", encoding="utf8") as f:
for row in csv.DictReader(f):
key = (row.get(key_field) or "").strip().upper()
if key:
records[key] = row
return recordsThis returns a dictionary keyed by the cleaned ID. Dictionary keys behave like a set, so I get fast lookups and I keep the full row for later comparisons. If the same key shows up twice, the last row wins, which is why I also check for duplicates separately (more on that below).
Step two: find what is missing and what is extra
dispatch = load("dispatch.csv", "order_id")
erp = load("erp.csv", "OrderNumber")
dispatch_keys = set(dispatch)
erp_keys = set(erp)
missing_in_erp = sorted(dispatch_keys.difference(erp_keys))
missing_in_dispatch = sorted(erp_keys.difference(dispatch_keys))
in_both = dispatch_keys.intersection(erp_keys)
print(f"{len(missing_in_erp)} orders in dispatch but not in ERP")
print(f"{len(missing_in_dispatch)} orders in ERP but not in dispatch")Sorting the output matters more than it seems. A sorted list of IDs is something a person can scan, paste into a ticket, or compare against tomorrow's run.
Step three: compare the records that exist in both
Matching keys are only half the answer. A record can exist in both systems and still disagree on quantity or status. For the keys in both, I compare the fields that are supposed to match:
FIELDS = [("qty", "Quantity"), ("status", "Status")]
mismatches = []
for key in sorted(in_both):
left, right = dispatch[key], erp[key]
for left_field, right_field in FIELDS:
a = (left.get(left_field) or "").strip().lower()
b = (right.get(right_field) or "").strip().lower()
if a != b:
mismatches.append((key, left_field, a, b))The FIELDS list maps column names between the two files, since two systems almost never use the same headers. Adding a new field to check is one line.
Step four: catch duplicates before they hide problems
Because the loader keeps only one row per key, duplicates disappear silently. I check for them with a set that remembers what it has already seen:
def duplicate_keys(path, key_field):
seen, dupes = set(), set()
with open(path, newline="", encoding="utf8") as f:
for row in csv.DictReader(f):
key = (row.get(key_field) or "").strip().upper()
if key in seen:
dupes.add(key)
seen.add(key)
return sorted(dupes)A duplicate order in one system is often the real reason the totals do not match, so I print this list first.
Writing the report
I write the results to one CSV with a column that says what kind of problem each row is: missing in ERP, missing in dispatch, duplicate, or field mismatch. A single file with a type column is easier to filter and hand to someone than four separate files.
What I learned doing this for real
Normalize keys before you compare anything, or you will chase ghosts. Keep the full rows, not just the IDs, because the next question is always "what does the record actually say?" Use method names like difference and intersection so the script reads like the question you are answering. And sort every list you print.
I still use this pattern in my AI evaluation work, where a batch of submitted samples has to line up with a batch of scored ones. The data changes, but the question stays the same: what is in one list, what is in the other, and what disagrees. Sets answer it in a few lines.