[Tutor] sorting a list of dictionaries

Kent Johnson kent37 at tds.net
Fri Apr 15 17:15:38 CEST 2005


Gooch, John wrote:
> Ken, 
> 
> I misspoke when I said these were lists of dictionaries, they are actually
> lists of object that have a "getSize()" getter function that returns the
> size of their contents, which I would like to use for sorting.

It the objects are instances of SomeClass, I think you could use
lst.sort(key=SomeClass.getSize)

otherwise you could use
lst.sort(key=lambda x: x.getSize())

Kent

> 
> Thank You,
> 
> John A. Gooch
> Systems Administrator
> IT - Tools
> EchoStar Satellite L.L.C.
> 9601 S. Meridian Blvd.
> Englewood, CO  80112
> Desk: 720-514-5708 
> 
> 
> -----Original Message-----
> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
> Of Kent Johnson
> Sent: Wednesday, April 13, 2005 3:52 AM
> Cc: tutor at python.org
> Subject: Re: [Tutor] sorting a list of dictionaries
> 
> 
> 
>>-----Original Message-----
>>From: sigurd at 12move.de [mailto:sigurd at 12move.de]
>>Sent: Thursday, December 09, 2004 12:19 PM
>>To: tutor at python.org
>>Subject: Re: [Tutor] sorting a list of dictionaries
>>
>>
>>On  9 Dez 2004, ljholish at speakeasy.net wrote:
>>
>>
>>
>>>I have a list of dictionaries, each representing info about a file,
>>>something like:
>>>
>>>[{'name':'foo.txt','size':35}, {'name':'bar.txt','size':35}, ...]
>>>
>>>I want to present a sorted list of all the files' data, sorting on the
>>>keys 'name' or 'size'. The file 'name' s should be unique (I'm hoping) 
>>>across all the dictionaries. Can someone point me towards an efficient 
>>>solution for accomplishing the sort? (The list has 1000s of files).
>>
>>
>>That's easy to achieve, since sort takes a custom sort function as 
>>optional argument.  Now you need only a function which takes the 
>>values of the fileds and compares them.
>>
>>E.g.
>>
>>lst.sort(lambda m, n: cmp(m.get(field), n.get(field)))
>>where field is either 'name' or 'size'.
> 
> 
> In Python 2.4 a more efficient way of doing this is to use the key parameter
> to sort() with an 
> itemgetter function:
> 
> from operator import itemgetter
> lst.sort(key=itemgetter('field'))
> 
> Kent
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



More information about the Tutor mailing list