← Lesson
Reduce Is the Product
Joeven
Run
Reset
Python loads on first run
def reduce_rows(rows, expect_ids): by_id = {} dropped = [] for r in rows: if not r.get("ok"): dropped.append(r.get("id")) continue by_id[r["id"]] = r["label"] missing = [i for i in expect_ids if i not in by_id] counts = {} for lab in by_id.values(): counts[lab] = counts.get(lab, 0) + 1 winner = None if counts: winner = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[0][0] return { "winner": winner, "n": len(by_id), "missing": missing, "dropped": dropped, } rows = [ {"id": "a", "ok": True, "label": "sev3"}, {"id": "b", "ok": True, "label": "sev1"}, {"id": "c", "ok": False, "label": None}, {"id": "a", "ok": True, "label": "sev3"}, ] print(reduce_rows(rows, ["a", "b", "c", "d"]))
Run to execute this in your browser. Nothing is sent to a server.