Dedup, group and join by hand

Part of the free LogicWiz Data Engineering course, Module 3: Python for data wrangling. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 4:10 on Friday. The warehouse is down for maintenance until Monday, and Tess needs one table before she leaves: every order from the first week of June, once, with its latest status and the customer's country. The landing folder holds 68 rows for 40 orders. Nora slides her chair over: "No pandas, no SQL. You have dicts. That is enough."

You'll learn to

  • Keep the latest row per key, with ties broken on purpose
  • Group and join two lists by hand: inner, left and anti-join
  • Explain how a dict finds a key, and which keys are equal
  • Size the in-memory side of a join before it runs

Learn

A dict is all you need

Three jobs stand between you and Tess's table. Remove the duplicates. Add things up per group. Join orders to customers. In plain Python all three use one tool: a dict keyed by the thing you care about.

Why a dict and not a list? Finding each order's customer by scanning the customer list costs 68 × 30 = 2,040 comparisons here. For a million orders and a million customers it is a trillion, and the job never finishes.

A dict does not scan. It jumps straight to the right entry, and a lookup costs about the same whether the dict holds ten entries or ten million. Build it once, and every order costs one lookup.

Step one: load the week and count

import csv, glob

rows = []
for path in sorted(glob.glob("landing/orders/*.csv")):
    with open(path, newline="") as f:
        for r in csv.DictReader(f):
            r["file"] = path.split("/")[-1]
            rows.append(r)

print("rows:", len(rows))
print("orders:", len({r["order_id"] for r in rows}))

exact = {(r["order_id"], r["customer_id"], r["order_ts"], r["status"], r["updated_at"]) for r in rows}
print("rows without exact repeats:", len(exact))

The numbers from Lesson 1.1: 68 rows, 40 orders. A set of tuples throws out exact repeats, so the 7 rows of the retry file disappear and 61 are left. But 61 rows for 40 orders is still too many: an order placed on Monday and shipped on Tuesday is two different rows. Those need a rule, not a set.

Keep the latest version

The rule: for each order, keep the row with the greatest updated_at.

Go through the rows once. Keep a dict with one entry per order: the best row seen so far. A new row takes the place only if its order is not in the dict yet, or if it is newer than the row already there.

Comparing the timestamps as text works on these files, because every one has the same fixed form, 2025-06-03T09:26:57Z, and that form sorts as text in time order. The day two sources mix forms, such as 2025-06-03 09:26:57 or 3/6/2025, text comparison lies. Turn them into real datetimes first (Lesson 3.6).

One winner per order

Five rows are read one at a time into a dict that keeps the newest row per order: a newer row replaces an older one, an equal timestamp keeps the first row, and an older row that arrives last is rejected.

  1. The first row. Order 1008 is not in the dict yet, so the row goes in.

  2. A newer row for the same order. 3 June is greater than 2 June, so the row replaces the entry. Still one entry for 1008.

  3. The retry copy. Same order, same timestamp. > is false for equal values, so the row already there stays. A tie keeps the first one seen.

  4. A new order. 1016 is not in the dict, so it goes in. Two entries now.

  5. An old row that arrives last. Say a late file brings the 3 June version of 1016. It is older than the entry, so it loses, although it was read last. Latest wins, not last.

The left box is the input, top to bottom. The right box is the dict after each row. It never holds more than one entry per order.

"Last write wins" is not "latest wins". Writing latest[k] = r for every row keeps whichever row you happened to read last. That depends on file order, and files do not arrive in time order: order 1016 was placed on 3 June but first appears in the 5 June drop. Always compare the version column, and break ties on purpose.

Step two: one row per order

import csv, glob

rows = []
for path in sorted(glob.glob("landing/orders/*.csv")):
    with open(path, newline="") as f:
        for r in csv.DictReader(f):
            r["file"] = path.split("/")[-1]
            rows.append(r)

latest = {}
for r in rows:
    k = r["order_id"]
    if k not in latest or r["updated_at"] > latest[k]["updated_at"]:
        latest[k] = r

print(len(rows), "rows ->", len(latest), "orders")
for k in ["1008", "1016"]:
    w = latest[k]
    print(k, w["status"], w["updated_at"], w["file"])

68 rows in, 40 orders out. Order 1016 is the interesting one: it was placed on 3 June but only turned up in the 5 June file, and changed again on 6 June. The comparison picks the 6 June version because of its timestamp, not because of the order the files were read in.

Ties: decide on purpose

Two versions with the same updated_at are a tie. When one is an exact copy of the other, it does not matter which survives. When they differ, you need a rule, such as "the row from the later file wins".

Python makes that rule one line: compare tuples. (r["updated_at"], r["file"]) compares the timestamps first and looks at the file names only when the timestamps are equal.

Tuples do a second job. An order line is identified by its order and its line number together, not by either alone. Such a pair is a composite key, and a tuple can be a dict key (a list cannot, because it can change): lines[(r["order_id"], r["line_no"])] = r.

Order 1008, before and after

filestatusupdatedatkept?
2025-06-02.csvplaced2025-06-02T07:26:57Zno: older
2025-06-03.csvshipped2025-06-03T09:26:57Zyes
2025-06-03retry.csvshipped2025-06-03T09:26:57Zno: a tie, and keeps the first

The third row is a tie with the second. Because the comparison is strictly >, the row seen first stays. That is a decision, even if you did not mean to make one. With the tuple rule above, the retry file would win instead.

Under the hood: how a dict finds a key

Why is a lookup so cheap? Think of a coat check. You hand over a ticket number and the attendant walks straight to that hook. Nobody searches the racks.

A dict works the same way. Python turns the key into a number, its hash. The last few bits of the hash pick a slot in a small table. The slot points to an entry that holds the hash, the key and the value. Python checks that the key really matches, then hands back the value.

Sometimes two keys want the same slot. That is a collision, and the dict then tries other slots in a fixed order. Step through one lookup.

Looking up order 1002

A dict of three orders is drawn as an index of eight slots above three entries: the lookup of 1002 hashes to slot 2, slot 2 points to entry 1 where hash and key match, and a new key 1009 collides with order 1001 in slot 1.

  1. The dict before the lookup. Three orders are stored. The index has 8 small slots, and three of them point at entries. The entries sit in the order they were added.

  2. Hash, then slot. You ask for latest[1002]. The hash of the int 1002 is 1002, and its last three bits, 1002 & 7, are 2. Go to slot 2.

  3. Slot to entry. Slot 2 says "entry 1". Python compares the stored hash, then the key with ==. Both match, so it returns the row. One jump, however big the dict is.

  4. A collision. Now add order 1009. 1009 & 7 is 1, and slot 1 already belongs to order 1001. The dict tries other slots in a fixed, scrambled order until it finds a free one.

The top row is the index, the list under it holds the entries. A sixth key would make this dict grow to 16 slots and copy every entry, which is why sys.getsizeof jumps from 224 to 352 bytes at the sixth key.

Equal keys are one key

The last step of a lookup is ==, and that has consequences.

Anything equal with an equal hash is the same key. 1, 1.0 and True are all equal and all hash to 1, so {1: "int", 1.0: "float", True: "bool"} ends up as {1: 'bool'}: the first key stays, the last value wins.

The reverse breaks joins. "101" and 101 are different keys, so ids read as text never meet ids stored as ints.

One more surprise. String hashes are scrambled differently each time Python starts (PYTHONHASHSEED), so a set of strings comes out in a different order on every run. A pipeline that must give the same output twice sorts before it writes.

Group by: the key is the group

Grouping is the same trick with a different value. The dict key is the group. The value is a running total.

collections.defaultdict(float) starts every new key at 0.0, so revenue[k] += amount works the first time a key appears. collections.Counter does the same for counting, and Counter.most_common(n) gives the top n.

Keep the totals honest. Money held as floats picks up tiny errors: 0.1 + 0.2 is 0.30000000000000004. Round when you report, or use Decimal (Lesson 3.6).

Revenue per order and orders per status

import csv
from collections import defaultdict, Counter

with open("data/order_items.csv", newline="") as f:
    items = list(csv.DictReader(f))

revenue = defaultdict(float)
for it in items:
    revenue[int(it["order_id"])] += int(it["qty"]) * float(it["unit_price"])

print(len(revenue), "orders with lines")
print("order 1012:", round(revenue[1012], 2))

with open("data/orders.csv", newline="") as f:
    orders = list(csv.DictReader(f))
print(Counter(o["status"] for o in orders).most_common(2))

79 of the 80 orders have lines. Order 1012 adds up to $142.44, the amount you chased in Lesson 1.2. And most_common(2) gives the two biggest groups: 29 delivered, 26 shipped.

Join: build once, probe once per row

A join by hand has two steps. Build an index on one side, usually the smaller one: products = {p["product_id"]: p for p in product_rows}. Then probe it while you loop over the other side: products.get(line["product_id"]).

What you do on a miss decides the kind of join. Skip the row: an inner join. Keep it, with None in the missing columns: a left join. Keep only the misses: an anti-join, the classic way to find orphans, such as an order line that points at a product nobody sells. Databases do the same thing and call it a hash join.

One warning about the build side. If its key repeats, the dict keeps only the last row for that key. Check len(index) == len(rows) after you build it.

Find the orphan line

import csv

with open("data/products.csv", newline="") as f:
    products = {int(p["product_id"]): p for p in csv.DictReader(f)}

with open("landing/order_items/2025-06-02.csv", newline="") as f:
    lines = list(csv.DictReader(f))

joined, orphans = [], []
for line in lines:
    p = products.get(int(line["product_id"]))
    joined.append({**line, "product_name": p["name"] if p else None})
    if p is None:
        orphans.append((line["order_id"], line["line_no"], line["product_id"]))

print(len(lines), "lines in,", len(joined), "lines out (left join)")
print("orphans:", orphans)

12 lines in, 12 lines out: a left join keeps the row count. The orphan is line 9 of order 1009, which points at product 999. An inner join would have dropped it silently, and the revenue would quietly shrink by $5. Note int(...) on both sides of the lookup.

A hash join by hand: build once, probe once per row

Products are read once into a dict, the build side; order lines stream past it one at a time, the probe side; each lookup ends as a hit or a miss, and what you keep decides inner, left or anti-join.

Read it left to right. The violet side is read once and kept in memory as a dict. The blue side streams past it one row at a time. The three boxes on the right are the three things you can do with a hit or a miss.

Remember: one row per key takes three decisions: the key, the rule (greatest updated_at) and the tie-break. And after every dedup or join, count the rows before and after.

Size the build side

Only the build side lives in memory, so it decides whether the join survives.

Say you index a million customers as {customer_id: whole_row}, each row a dict with eight text fields. The dict's own table is 40 MiB. The million int keys add 28 bytes each. And a million row dicts of several hundred bytes each bring the total to roughly 1 GB.

Now keep only what the join needs: {customer_id: country}. The table and the keys are the same, and the few country names are shared between customers. About 70 MB.

When even that does not fit, sort both sides by key and walk through them together: a sort-merge join. It needs almost no memory, and pays with the time to sort.

A million customers as the build side

Two bars compare the memory of indexing a million customers: about 1,000 MB when the dict holds whole row dicts, and about 70 MB when it holds only the country.

Rough sizes on 64-bit CPython 3.12. Both bars include the same 40 MiB dict table and 28 MB of int keys. The whole difference is a million row dicts you did not need.

Numbers to remember

WhatOn 64-bit CPython 3.12Good to know
An empty dict {}64 byteswith one int key: 224 bytes
Room in a small dict5 entries in 8 slotsthe sixth key grows it to 16 slots: 224 to 352 bytes
When a dict growsat about two thirds fullso its memory jumps in steps
One entry24 bytes: hash, key pointer, value pointer16 bytes when every key is a str, which caches its own hash
One index slot1, 2, 4 or 8 bytes, by table sizethe entries keep insertion order (a dict has been two arrays since Python 3.6)
A million int keys41,943,128 bytes (40 MiB)before the key and value objects themselves
Postgres hash joinsized against workmemsplits into batches on disk when it does not fit
Spark broadcast hash joinspark.sql.autoBroadcastJoinThreshold: 10 MBonly a side below it is shipped to every machine as a lookup map
itertools.groupbygroups adjacent equal keys onlyso sort first, like a sort-merge join: O(n log n) time, against O(n) for one pass with a dict
float("nan") as a keynot equal to itselffound again only through the very same object

What you wrote by hand is Module 2's ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY updated_at DESC). Delta Lake's MERGE fails when two source rows match the same target row, so teams deduplicate exactly like this before they merge.

What changed at SwiftKart

At 5:20 Tess has her table: 40 orders, each once, each with its latest status and the customer's country. Three dicts did it. One kept the winner per order. One added up revenue per group. One held the customers while the orders streamed past.

You leave two checks in the script: every index is as long as the list it was built from, and the row count is printed before and after each join.

All of this worked because 68 rows fit in memory many times over. Dana's full export does not. The next lesson is about files bigger than your memory, and the Python feature built for them: generators.

In one line

A dict keyed by the thing you care about removes duplicates, groups and joins in one pass: compare the version, break ties on purpose, and keep the in-memory side small.

Interview corner

What happens inside Python when you look up a key in a dict, and what does that mean for a hand-written join?

CPython hashes the key, masks the hash to a slot in a sparse index, follows it to an entry in a dense insertion-ordered array, and compares the stored hash and then ==; a taken slot means probing other slots. Lookups are O(1) on average, so building a dict on the smaller side and probing from the other is a linear hash join. The cost is memory: the table grows at two thirds full, a million int keys is about 40 MiB of table alone, and every key and value object comes on top, so I project the build side to only the join key and the columns I need, or switch to a sort-merge when it cannot fit.

How do you deduplicate records in Python, keeping the latest version per key?

One pass with a dict from key to the current winner: a row replaces the winner when its version column, such as updated_at, is greater. I compare a tuple like (updated_at, source_file) so ties are broken on purpose, and I make sure the timestamps are in one format or parsed first. It runs in O(n) time and O(number of keys) memory.

How would you join two large lists of dicts without pandas?

A hash join: build a dict on the smaller side keyed by the join key, then loop over the bigger side and look each row up. A miss means drop it (inner join), keep it with None (left join) or keep only it (anti-join). I check the build side's key is unique, because a dict silently keeps only the last row per key.

Your dedup gives different results on two runs over the same data. Why?

Usually a tie: two versions share the same timestamp and the winner depends on reading order, which can change between runs (file listing order, parallel reads). The fix is a deterministic tie-breaker, such as the source file, an ingestion sequence number or a status rank, so the same input always gives the same output.