[Tutor] user defined compare for sorting
Remco Gerlich
scarblac@pino.selwerd.nl
Tue, 10 Apr 2001 00:49:57 +0200
On 0, Rick Pasotto <rick@niof.net> wrote:
> I have a list of dictionaries. How can I specify at runtime the key to
> use for sorting the list?
>
> lst[ [ 'A':'a', 'B':'2', 'C':'z' ]
> [ 'A':'b', 'B':'3', 'C':'x' ]
> [ 'A':'c', 'B':'1', 'C':'y' ] ]
>
> How can I pass 'A', 'B', or 'C' to 'key' in the compare function?
>
> def mycmp(a,b): cmp(a[key],b[key])
(The above isn't correct, I assume you meant { curly braces } around the
dicts, and the mycmp needs a "return").
I understand you want to be able to sort the list on different keys.
Make a function that returns a function that sorts on some key:
def make_sort_function(key):
def sort_func(a, b, key=key):
return cmp(a[key], b[key])
return sort_func
cmp_func works as we want it to work because it gets key as a default
argument.
Now you can do, say,
lst.sort(make_sort_function('A'))
'lambda' is a way to make functions on the fly. The same thing could like
like this:
lst.sort(lambda a,b,key='A': cmp(a[key],b[key]))
It's up to you to choose the one you find easier to understand.
If you don't understand how this works, play around with make_sort_function
in the interpreter...
--
Remco Gerlich