Python Practice › Iterator & Generator Programs › Program 20
Group consecutive items
Write a Python program that groups log lines by level with itertools.groupby.
Output
ERROR ['db', 'disk'] INFO ['ok', 'start']
Approach
groupbygroups consecutive equal keys, so sort first.
Solution
from itertools import groupby logs = [("ERROR", "db"), ("INFO", "start"), ("ERROR", "disk"), ("INFO", "ok")]for level, group in groupby(sorted(logs), key=lambda x: x[0]): print(level, [msg for _, msg in group])Output
ERROR ['db', 'disk'] INFO ['ok', 'start']
Learn the concept
New to this topic? Read the lesson, then come back.