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

ian douglas ian.douglas at iandouglas.com
Mon Aug 1 22:15:57 CEST 2011


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?

I hadn't seen the __dict__ property before for objects, and that allowed 
me to just build a simple list of dictionaries, which I could then run 
through the itemgetter() solution I'd found on StackOverflow.

Ian



More information about the Tutor mailing list