Skip to content

Instantly share code, notes, and snippets.

@panzi
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panzi/817356f5b1edd8cc236c to your computer and use it in GitHub Desktop.
Save panzi/817356f5b1edd8cc236c to your computer and use it in GitHub Desktop.
simple grouping function in Python
from collections import defaultdict
__all__ = 'group_by', 'index_by'
def group_by(iterable, key):
grouped = defaultdict(list)
for item in iterable:
grouped[key(item)].append(item)
return grouped
def index_by(iterable, key):
indexed = {}
for item in iterable:
indexed[key(item)] = item
return indexed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment