Last active
August 29, 2015 14:10
-
-
Save panzi/817356f5b1edd8cc236c to your computer and use it in GitHub Desktop.
simple grouping function in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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