[Answered ]-Python group a list of years, months to remove duplication of years

1👍

You can work with the groupby(…) function [Python-doc] of the itertools module [Python-doc]:

from itertools import groupby
from operator import itemgetter

years = purchase_orders.objects.filter(
    user=info.context.user
).values(
    year=ExtractYear('date'),
    month=ExtractMonth('date')
).order_by('year', 'month').distinct()

years = [
    (y, [ym['month'] for ym in yms])
    for y, yms in groupby(years, itemgetter('year'))
]

We thus first fetch the data from the database, and then post-process this by constructing a list of 2-tuples where the first item contains the year, and the second is a list of months for that year.

Leave a comment