Prerequisites: Python Itertools
Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.
Itertools.groupby()
This method calculates the keys for each element present in iterable. It returns key and iterable of grouped items.
Syntax: itertools.groupby(iterable, key_func)
Parameters:
iterable: Iterable can be of any kind (list, tuple, dictionary).
key: A function that calculates keys for each element present in iterable.Return type: It returns consecutive keys and groups from the iterable. If the key function is not specified or is None, key defaults to an identity function and returns the element unchanged.
Example 1:
# Python code to demonstrate # itertools.groupby() method import itertools L = [( "a" , 1 ), ( "a" , 2 ), ( "b" , 3 ), ( "b" , 4 )] # Key function key_func = lambda x: x[ 0 ] for key, group in itertools.groupby(L, key_func): print (key + " :" , list (group)) |
Output:
a : [('a', 1), ('a', 2)] b : [('b', 3), ('b', 4)]
Example 2 :
# Python code to demonstrate # itertools.groupby() method import itertools a_list = [( "Animal" , "cat" ), ( "Animal" , "dog" ), ( "Bird" , "peacock" ), ( "Bird" , "pigeon" )] an_iterator = itertools.groupby(a_list, lambda x : x[ 0 ]) for key, group in an_iterator: key_and_group = {key : list (group)} print (key_and_group) |
Output
{'Animal': [('Animal', 'cat'), ('Animal', 'dog')]} {'Bird': [('Bird', 'peacock'), ('Bird', 'pigeon')]}