from collections import OrderedDict ROLE_PRIORITY = {"lead": 0, "leader": 0, "organizer": 1, "collaborator": 2} ROLE_TITLES = {0: "Lead / Leader", 1: "Organizers", 2: "Collaborators"} def person_sort_key(person): role = (person.role or "").strip().casefold() return (ROLE_PRIORITY.get(role, 3), role if role not in ROLE_PRIORITY else "", person.order, person.pk or 0) def group_people(people): groups = OrderedDict() for person in sorted(people, key=person_sort_key): role = (person.role or "").strip() priority = ROLE_PRIORITY.get(role.casefold(), 3) key = priority if priority < 3 else role.casefold() if key not in groups: groups[key] = { "title": ROLE_TITLES[priority] if priority < 3 else role or "Other contributors", "people": [], } groups[key]["people"].append(person) return list(groups.values())