Python cookbook (data structure and algorithm) records grouped operation examples based on fields, pythoncookbook
This example describes how to group records by field in Python. We will share this with you for your reference. The details are as follows:
Problem:You want to group iterative data based on a dictionary or a specific Dictionary (such as a date) of an object instance.
Solution:itertools.groupby()
Functions are particularly useful when grouping data (the premise is to sort data in the target dictionary first)
Rows = [{'address': '192 N clark', 'date': '192/123'}, {'address': '192 N clark', 'date ': '2014/1/20180101'}, {'address': '2014/2 E 58th', 'date': '2014/2/20180101'}, {'address': '2014 N clark ', 'date': '2014/1/123'}, {'address': '2014/2 n ravenswood ', 'date': '2014/123'}, {'address ': '1970 W addison', 'date': '1970/123'}, {'address': '1970 n broadway ', 'date': '1970/123 '}, {'address': '1970 w granville ', 'date': '1970/123'},] from operator import itemgetterfrom itertools import groupbyrows. sort (key = itemgetter ('date') # first sort by date Field for date, items in groupby (rows, key = itemgetter ('date ')): # grouping by date print (date) for I in items: print ('', I) # If you simply group data by date, put it into a large data structure to allow random access, it would be better to use defaultdict to build a one-key multi-value dictionary # Example of building a multidictfrom collerom import defadicdictrows_by_date = defaultdict (list) # create a dictionary with one-click multi-value. for row in rows: rows_by_date [row ['date']. append (row) for r in rows_by_date ['2014/1/123']: print (r)
Running result:
07/01/2012 {'address': '5412 N CLARK', 'date': '07/01/2012'} {'address': '4801 N BROADWAY', 'date': '07/01/2012'}07/02/2012 {'address': '5800 E 58TH', 'date': '07/02/2012'} {'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'} {'address': '1060 W ADDISON', 'date': '07/02/2012'}07/03/2012 {'address': '2122 N CLARK', 'date': '07/03/2012'}07/04/2012 {'address': '5148 N CLARK', 'date': '07/04/2012'} {'address': '1039 W GRANVILLE', 'date': '07/04/2012'}{'address': '5412 N CLARK', 'date': '07/01/2012'}{'address': '4801 N BROADWAY', 'date': '07/01/2012'}
(The code is from Python Cookbook.)