[Python-talk] Help with custom sort
Kent Johnson
kent37 at tds.net
Sun Oct 14 16:17:04 EDT 2007
Cole Tuininga wrote:
> Hey folks - I'm still a bit rusty here and could use some help.
>
> I have a list of dictionaries that I want to sort based off of a key
> which I'll hypothetically call 'key'. I figured that I'd just write a
> small little comparison function to hand to sort.
A better way to do this is with the key= parameter to sort(). The
argument is a function that returns the proper key.
operator.itemgetter() is a factory that produces a function that will
fetch an indexed item from its argument. So if I understand your problem
you can do
from operator import itemgetter
dict_list.sort(key=itemgetter('key'))
More here:
http://personalpages.tds.net/~kent37/kk/00007.html
Kent
> Something along the
> lines of:
>
> dict_list = [<my list of dictionaries>]
>
> def sort_func(x, y):
> <magic here>
>
> dict_list.sort(sort_func)
>
> The thing is, I'd like to just compare the two strings in sort_func and
> I can't remember the syntax. In perl, I'd just do something like:
>
> sub sort_func {
> return $a{'key'} cmp $b{'key'};
> }
>
> The "cmp" function will take care of doing the string comparison and
> return the correct value of (-1, 0, 1). Is there a similar thing in
> Python that I'm just forgetting? Or am I stuck doing separate tests for
>> , =, and < ?
>
> Thanks in forgetfulness....
>
More information about the Python-talk
mailing list