Press "Enter" to skip to content

Python Program to Group Records Based on a Field

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

Hi, I am a full stack developer and writing about development. I document everything I learn and help thousands of people. foxinfotech.in is created, written, and maintained by me; it is built on WordPress, and hosted by Bluehost. Connect with me on Facebook, Twitter, GitHub, and get notifications for new posts.

Be First to Comment

    Leave a Reply

    Your email address will not be published. Required fields are marked *