Skip to content

Instantly share code, notes, and snippets.

@dhwthompson
Created January 18, 2010 09:48
Show Gist options
  • Save dhwthompson/279910 to your computer and use it in GitHub Desktop.
Save dhwthompson/279910 to your computer and use it in GitHub Desktop.
def group_by(source, key_func):
acc = {}
for item in source:
acc.setdefault(key_func(item), []).append(item)
return acc
if __name__ == '__main__':
print group_by([(1, 2), (1, 3), (2, 3), (2, 4)], lambda x: x[0])
print group_by([(1, 2), (1, 3), (2, 3), (2, 4)], lambda x: x[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment