Andrew
Andrew

Reputation: 51

Most efficient way to sort/categories objects in list based on object attribute

I have an unsorted list of objects that each have a end_date attribute.

The list just looks like [obj1, obj2, obj3, <...>] in no specific order.

I want to end up with a list that looks like this:

[["Saturday, May 5", [obj3, obj5]], ["Monday, May 7", [obj1, obj8, obj9]] ... etc ]

Basically just a list of lists, where the "key" is the date from the objects and the value for that key is a list of objects that have that date. Don't worry about the date formatting, that's just an easy datetime manipulation. I know it's relatively easy to do with a dictionary, but I need to end up with a list sorted by the keys, and you can't do this with dictionaries (at least not with Python 2.6 IIRC)

What is the most efficient way to do this? I've been muddling through some solutions with a bunch of for loops, but it seems like I'm going about it wrong.

Upvotes: 0

Views: 999

Answers (3)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798754

itertools.groupby(sorted(L, key=operator.attrgetter('end_date')),
  key=operator.attrgetter('end_date'))

Upvotes: 1

Stephen
Stephen

Reputation: 49196

You said you know how to get it to a dict. So, just sort the results:

d = ToDict(...)
sorted_values = sorted(((date,list) for date,list in d.iteritems()))

Should be O(n log n)

You can provide a sorting method to sorted as well, if you want to manipulate your date type. See a sorting in python overview.

Upvotes: 0

Florian Diesch
Florian Diesch

Reputation: 1025

Put it into a dictionary, then use l=list(dictionary.iteritems()) to get the list and l.sort() to sort it

Upvotes: 0

Related Questions