NHK/
SNIPPET / pythonREFERENCE

Python itertools groupby

Allows you to group data by a key function

Python ยท Itertools
from itertools import groupby
from operator import itemgetter

transactions = [
    {'date': '2024-02-20', 'amount': 100},
    {'date': '2024-02-20', 'amount': 50},
    {'date': '2024-02-21', 'amount': 75},
    {'date': '2024-02-21', 'amount': 120},
    {'date': '2024-02-22', 'amount': 200},
]

transactions.sort(key=itemgetter('date'))

grouped_transactions = {date: list(group) for date, group in groupby(transactions, key=itemgetter('date'))}

for date, group in grouped_transactions.items():
    print(f"Date: {date}")
    for transaction in group:
        print(f"  - Amount: {transaction['amount']}")

This prints:

Date: 2024-02-20
  - Amount: 100
  - Amount: 50
Date: 2024-02-21
  - Amount: 75
  - Amount: 120

Of note here is that the collection needs to be sorted first. We’re also using itemgetter here, which is a more performant alternative to lambda x: x['date'].