
Problem –
You have a list of dictionaries and you want to group the data by a key in the dictionary.
customers = [{'customer':1, 'net sales': 39.5, 'method':'Discover'},
{'customer':2, 'net sales': 102.4, 'method':'Proprietary'},
{'customer':3, 'net sales': 22.5, 'method': 'Proprietary'},
{'customer':4, 'net sales': 100.4, 'method': 'Proprietary'},
{'customer':5, 'net sales': 54.0, 'method': 'MasterCard'},
{'customer':6, 'net sales': 75.0, 'method': 'Discover'}]
Solution –
Let’s say that you want to group the data by the method of payment. This can be done using the itertools.groupby function. First we have to sort the data by the desired key in this case ‘method’ and then use itertools.groupby.
In [10]: from operator import itemgetter
In [11]: from itertools import groupby
In [12]: # sort the data by desired key first
In [13]: customers.sort(key=itemgetter('method'))
In [14]: # then iterate in groups
In [15]: for method, items in groupby(customers, key=itemgetter('method')):
...: print(method)
...: for i in items:
...: print(' ', i)
...:
Discover
{'customer': 1, 'net sales': 39.5, 'method': 'Discover'}
{'customer': 6, 'net sales': 75.0, 'method': 'Discover'}
MasterCard
{'customer': 5, 'net sales': 54.0, 'method': 'MasterCard'}
Proprietary
{'customer': 2, 'net sales': 102.4, 'method': 'Proprietary'}
{'customer': 3, 'net sales': 22.5, 'method': 'Proprietary'}
{'customer': 4, 'net sales': 100.4, 'method': 'Proprietary'}