# create a list of json dictionaries with the key being a tuple of (Unit, # Structure) and the value being a set of each textile tool # in that unit, with the initial entry being an # empty set and further objects appending # to the set, then print Unit, Structure: Object1, Object2 ... import csv import json def csv_sort_into_units(rows): results = {} for row in rows: key = (row["Unit"], row["Structure"]) if not key in results: results[key] = [] results[key].append(row) return results with open("KaranisExcavationRecordsTextile.csv") as f: reader = csv.DictReader(f) context_rows = csv_sort_into_units(reader) context_dict = {} for context_key, rows in context_rows.items(): (Unit, Structure) = context_key context = {"Unit" : Unit, "Structure" : Structure} items = set() for row in rows: if row["ObjectName"]: items.add(row["ObjectName"]) context["items"] = list(items) context_dict[Unit + "_" + Structure] = context with open("Assemblages.json", "w") as f_write: f_write.write(json.dumps(context_dict, indent=2))