Python Program to Group Records Based on a Field

  • Post author:
  • Post category:Python
  • Reading time:2 mins read

Here is an example of a Python program to group records based on a field in a dictionary.

Python GROUPBY Example to Group Dictionary Records on a Field

The following Python program will group the records on the date field.

rows = [
    {'address': '5212 N SHATIN', 'date': '09/01/2019'},
    {'address': '5348 N SHATIN', 'date': '09/04/2019'},
    {'address': '5500 E FOTAN', 'date': '09/02/2019'},
    {'address': '2222 N TST', 'date': '09/03/2019'},
    {'address': '5595 N CENTRAL', 'date': '09/02/2019'},
    {'address': '1020 W CAUSWAYBAY', 'date': '09/02/2019'},
    {'address': '4821 N TUNMUN', 'date': '09/01/2019'},
    {'address': '1029 W TUENWAN', 'date': '09/04/2019'},
]

from itertools import groupby

rows.sort(key=lambda r: r['date'])
for date, items in groupby(rows, key=lambda r: r['date']):
    print(date)
    for i in items:
        print('    ', i)

# Example of building a multidict
from collections import defaultdict

print('Created a dictionary for date 09/01/2019')

rows_by_date = defaultdict(list)
for row in rows:
    rows_by_date[row['date']].append(row)

for r in rows_by_date['09/01/2019']:
    print(r)

Output:

09/01/2019
{'address': '5212 N SHATIN', 'date': '09/01/2019'}
{'address': '4821 N TUNMUN', 'date': '09/01/2019'}
09/02/2019
{'address': '5500 E FOTAN', 'date': '09/02/2019'}
{'address': '5595 N CENTRAL', 'date': '09/02/2019'}
{'address': '1020 W CAUSWAYBAY', 'date': '09/02/2019'}
09/03/2019
{'address': '2222 N TST', 'date': '09/03/2019'}
09/04/2019
{'address': '5348 N SHATIN', 'date': '09/04/2019'}
{'address': '1029 W TUENWAN', 'date': '09/04/2019'}
Created a dictionary for date 09/01/2019
{'address': '5212 N SHATIN', 'date': '09/01/2019'}
{'address': '4821 N TUNMUN', 'date': '09/01/2019'}

Process finished with exit code 0

See also:

Vinish Kapoor

An Oracle Apex Consultant, Oracle ACE, and founder of foxinfotech.in and orclqa.com a question and answer forum for developers.