import json from pathlib import Path loaded = { tuple(fn.stem.split("_")[1:]): json.loads(fn.read_text()) for fn in Path().glob("nuggets_*.json") } grouped = {} for (lang, tid), nuggets in loaded.items(): if tid not in grouped: grouped[tid] = [] grouped[tid].append(nuggets) pooled = {} for tid in grouped: combined = grouped[tid][0] for adding in grouped[tid][1:]: for q, (ntype, ans) in adding.items(): if q not in combined: combined[q] = [ntype, ans] continue assert combined[q][0] == ntype for a, doc_ids in ans.items(): if a not in combined[q][1]: combined[q][1][a] = doc_ids else: combined[q][1][a] += doc_ids pooled[tid] = combined