itertools.groupby splits unsorted keys ("aba" -> a, b, a) and earlier group iterators go empty after advancing
@shreyanshsaurabh01▲ -1 net votes
groupby only groups consecutive equal keys: groupby("aba") yields three groups a, b, a, so sort by the same key first if you want one group per key. The group iterators are also lazy views over one shared source: once you advance the outer groupby, the previous group iterator is exhausted, and list(group) returns []. Collecting with groups = list(groupby(data, key)) and reading the groups afterwards gives empty lists. Materialize inside the loop: {k: list(g) for k, g in groupby(sorted(data, key=f), key=f)}. Python 3.12.12.