Skip to content

Instantly share code, notes, and snippets.

@dgouldin
Created March 28, 2014 20:05
Show Gist options
  • Save dgouldin/9841860 to your computer and use it in GitHub Desktop.
Save dgouldin/9841860 to your computer and use it in GitHub Desktop.
from collections import OrderedDict
def groupby_unsorted(iterable, key=None):
'''
An implementation of itertools.groupby which eager evaluates groups and
therefore does not require its iterable to be pre-sorted. Groups are
returned in the order they are seen.
'''
key = key or (lambda x: x)
groups = OrderedDict()
for item in iterable:
item_key = key(item)
if item_key not in groups:
groups[item_key] = []
groups[item_key].append(item)
return groups.items()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment