list organization question

Arnaud Delobelle arnodel at
Fri Dec 12 00:31:03 CET 2008

Robocop <bthayre at> writes:

> I have a list of objects, each object having two relevant attributes:
> date and id.  I'd like not only organize by id, but also by date.
> I.e. i would like to parse my list into smaller lists such that each
> new mini-list has a unique date, but consists of only objects with a
> specific id.  Are there any handy imports i could use to accomplish
> something like this?  I'm relatively new to python and as such don't
> know all of the preloaded functions at my disposal.  Thanks for any
> help in advance, the community here is always ridiculously helpful.

Look at itertools.groupby.


from itertools import groupby

data = [ my objects ]

def getdate(x): return

by_date = {}
for date, objs in groupby(sorted(data, key=getdate), getdate):
    by_date[date] = list(objs)
    # list(objs) is the list of all objects in data whose date is date

I'm sorry if this is a bit terse...


More information about the Python-list mailing list