brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's itertools.groupby only groups neighbours, so sort first

Python
~/tips/tip-python-groupby-needs-sorted

from itertools import groupby

Avoid duplicate groups from itertools.groupby by sorting on the same key first.

itertools.groupby looks like SQL’s GROUP BY, and that’s exactly why it trips people up. It only groups items that sit next to each other.

from itertools import groupby

data = ["b1", "a1", "b2", "a2"]
first = lambda s: s[0]

print([(k, list(g)) for k, g in groupby(data, key=first)])
# [('b', ['b1']), ('a', ['a1']), ('b', ['b2']), ('a', ['a2'])]

print([(k, list(g)) for k, g in groupby(sorted(data, key=first), key=first)])
# [('a', ['a1', 'a2']), ('b', ['b1', 'b2'])]

The first call gives you four groups, with ‘b’ and ‘a’ each showing up twice. Sort on the same key function first and you get the two groups you expected.

The unsorted behaviour is handy on purpose sometimes. I like it for collapsing runs in a log, like several identical lines in a row, where the order matters and you want each run counted separately.

There’s a second trap: each group is an iterator that shares data with the main one. As soon as groupby moves on to the next key, the previous group is gone. If you need the items later, turn them into a list right away, like the list(g) above does. And if you don’t care about order at all, a defaultdict(list) is often simpler.

Further reading: itertools.groupby

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link