itertools.groupby in Python

Python Methods and Functions

Creates an iterator over the grouped elements of the passed object.

itertools.groupby (iterable, key = None)

-> iterator [ tuple [Any, iterator]]

iiterable - An object whose elements you want to group.

key = None - A function that calculates and returning the grouping key for each item. If not specified, the identity function is used (returns the element itself). 

in key . See sorted () .

Function behavior is similar to the uniq filter on Unix ... Each time the value returned by the key function changes, a new group is created. Therefore, it is advisable to sort the items using the same function. Thus, the behavior differs from the GROUP BY behavior in SQL , which groups elements regardless of their order.

This function produces two-element tuples
First element: the value returned by the key function. 
Second element: an iterator over the objects in the group. 

  from itertools import groupby 

def grouper (item):
"" "We will use this function to group sorting. "" "
return item [' country']

data = [
{'city':' Moscow', 'country':' Russia'},
{ 'city':' Novosibirsk', 'country':' Russia'},
{'city':' Beijing', 'country':' China'},

# Pre-sort.
data = sorted (data, key = grouper)

for key, group_items in groupby (data, key = grouper):
print ('Key:% s'% key)
for item in group_items:
print ('Item:% s'% item)

' ''
Key: China
Item: {'city':' Beijing', 'country':' China'}
Key: Russia
Item: {'city':' Moscow', 'country':' Russia'}
Item: {'city':' Novosibirsk', 'country':' Russia'}
'' '

Get Solution for free from DataCamp guru