groupby — groups consecutive elements by a key function.
1import itertools23# Group sorted data4data = [5 {"type": "A", "value": 1},6 {"type": "B", "value": 2},7 {"type": "A", "value": 3},8 {"type": "B", "value": 4},9]1011# Must sort by key first!12data.sort(key=lambda x: x["type"])1314for key, group in itertools.groupby(data, key=lambda x: x["type"]):15 print(f"{key}: {[item["value"] for item in group]}")16# A: [1, 3]17# B: [2, 4]1819# Simple grouping20numbers = [1, 1, 2, 2, 2, 3, 3]21for key, group in itertools.groupby(numbers):22 print(f"{key}: {list(group)}")23# 1: [1, 1]24# 2: [2, 2, 2]25# 3: [3, 3]
Key point: Data MUST be sorted by the grouping key first, or groups will be split.