Skip to content

Instantly share code, notes, and snippets.

@carlosequiz
Created September 9, 2019 19:51
Show Gist options
  • Save carlosequiz/e13d34ae440564a47a30e1e916964366 to your computer and use it in GitHub Desktop.
Save carlosequiz/e13d34ae440564a47a30e1e916964366 to your computer and use it in GitHub Desktop.
import itertools
from operator import itemgetter
sorted_animals = sorted(animals, key=itemgetter('size'))
animals = [{'name':'cow', 'size':'large'},{'name':'bird', 'size':'small'},{'name':'fish', 'size':'small'},{'name':'rabbit', 'size':'medium'},{'name':'pony', 'size':'large'},{'name':'squirrel', 'size':'medium'},{'name':'fox', 'size':'medium'}]
for key, group in itertools.groupby(sorted_animals, key=lambda x:x['size']):
print key,
print list(group)
# large [{'name': 'cow', 'size': 'large'}, {'name': 'pony', 'size':'large'}]
# medium [{'name': 'rabbit', 'size': 'medium'}, {'name': 'squirrel', 'size':'medium'}, {'name': 'fox', 'size': 'medium'}]
# small [{'name': 'bird', 'size': 'small'}, {'name': 'fish', 'size': 'small'}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment