Dict Keys Give Stable Dedupe

Deduplicate records by choosing a key function and relying on dict insertion order: first-wins and last-wins are both one pass with no aux dedupe type.

PythonData Integrity

Code

pythonsnippet
23 lines
records = [
    {"user": "ada", "action": "login", "ts": "10:00"},
    {"user": "ada", "action": "login", "ts": "10:01"},
    {"user": "ada", "action": "logout", "ts": "10:05"},
    {"user": "lee", "action": "login", "ts": "10:02"},
]

# 键函数决定“保留哪条”:这里保留每个 (user, action) 时间最早的记录
first_seen = {}
for row in records:
    key = (row["user"], row["action"])
    if key not in first_seen or row["ts"] < first_seen[key]["ts"]:
        first_seen[key] = row

# dict 保持插入序:去重结果顺序 = 键首次出现顺序
deduped = list(first_seen.values())
print("before:", len(records), "after:", len(deduped))
for row in deduped:
    print(row["user"], row["action"], row["ts"])

# 变体:保留最后一条 —— 一次推导直接覆盖
last_seen = {(r["user"], r["action"]): r for r in records}
print("last-write wins:", sorted(k[1] for k in last_seen))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

before: 4 after: 3
ada login 10:00
ada logout 10:05
lee login 10:02
last-write wins: ['login', 'login', 'logout']

How the snippet works

Repetition is confined to for row in records — the rest of the file is straight-line.

Top-level bindings records, first_seen, deduped, last_seen hold the demo state — nothing sits inside a function scope.

Applying it

The demo output is labeled (before:, last-write wins:); each label names the call that printed it.

Statements that matter

if key not in first_seen or row["ts"] < first_seen[key]["ts"]:
    first_seen[key] = row
last_seen = {(r["user"], r["action"]): r for r in records}
for row in deduped:
    print(row["user"], row["action"], row["ts"])

Interactive Tools for This Topic

FAQ

Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. Its state lives in module-level bindings: `records`, `first_seen`, `deduped`.