[Tutor] Question about sorting a list within a dictionary within a list

Peter Otten __peter__ at web.de
Mon Aug 1 22:49:51 CEST 2011


ian douglas wrote:

> On 08/01/2011 01:03 PM, Peter Otten wrote:
>> ian douglas wrote:
>>
>>> I'm using the Bono library for talking to EC2, and I'm getting a list of
>>>
>>> I cannot help you with the django or boto part.
> 
> Well, I suppose that using django/bono wasn't really relevant to the
> question.
> 
> I appreciate the feedback though, I'll definitely keep it in mind for
> future projects. The sort() and mykey() stuff you proposed looked neat.
> I'll dig into that stuff more to see how it works when I finish this
> project. I appreciate the LEGAL_SORTKEYS bit too, it was on my to-do
> list as well.
> 
> 
> In the end, I ended up flattening things a little, instead of having a
> list of objects, and those objects holding a list of instances, and each
> of those instances being objects themselves:
> 
>      reservations_bulk = conn.get_all_instances()
>      reservations_unsorted = [] ;
>      for reservation in reservations_bulk:
>          instance = reservation.instances[0].__dict__
>          reservations_unsorted.append(instance)
>      reservations = sorted(reservations_unsorted,
> key=itemgetter('launch_time'))
> 
> I'm sure there's an even cleaner way of doing the for loop too?

Untested:

from operator import attrgetter, itemgetter
from itertools import imap

firsts = imap(itemgetter(0), conn.get_all_instances())
reservations = sorted(firsts, key=attrgetter("launch_time"))

This gives you objects rather than the objects' __dict__s.



More information about the Tutor mailing list