Created
September 9, 2019 19:51
-
-
Save carlosequiz/e13d34ae440564a47a30e1e916964366 to your computer and use it in GitHub Desktop.
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
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