Showing posts with label group list of dict. Show all posts
Showing posts with label group list of dict. Show all posts

Thursday, 23 June 2016

Group dictionary key values in python

Here is a tutorial for group list of dictionary by dictionary key values.

First you needs to sort your list of dictionaries.

For Ex.
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'}] 

Here is my list of dictionary.
To sort lits of dictionary you can use following code.

import itertools
from operator import itemgetter
sorted_animals = sorted(animals, key=itemgetter('size'))

Then use following code to group your list of dictionary.

for key, group in itertools.groupby(sorted_animals, key=lambda x:x['size']):
    print key,
    print list(group)

After you will get following result.

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'}]

Enjoy, Your list of dictionary is group by dictionary key values.