This seems like a great time to use `itertools.group_by`.