[Tutor] user defined compare for sorting
D-Man
dsh8290@rit.edu
Mon, 9 Apr 2001 18:53:21 -0400
On Mon, Apr 09, 2001 at 04:34:52PM -0400, Rick Pasotto 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' ] ]
minor correction :
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])
Perhaps something like this would help :
def make_cmp( key ) :
return lambda a , b , key=key : cmp( a[key] , b[key] )
this_key = 'B' # figure out the key to use
lst.sort( make_cmp( this_key ) )
The function make_cmp returns a comparison function that uses the
particular key you specify as its argument.
>>> def make_cmp( key ) : return lambda a , b, key=key : cmp( a[key] , b[key] )
...
>>> lst = [ { 'A':'a', 'B':'2', 'C':'z' } ,{ 'A':'b', 'B':'3', 'C':'x' } ,
{ 'A':'c', 'B':'1', 'C':'y' } ]
>>> lst
[{'B': '2', 'C': 'z', 'A': 'a'}, {'B': '3', 'C': 'x', 'A': 'b'}, {'B': '1', 'C':
'y', 'A': 'c'}]
>>> f = make_cmp( 'B' )
>>> print f
<function <lambda> at 007A843C>
>>> lst.sort( f )
>>> print lst
[{'B': '1', 'C': 'y', 'A': 'c'}, {'B': '2', 'C': 'z', 'A': 'a'}, {'B': '3', 'C':
'x', 'A': 'b'}]
>>>
Now try and do that as quickly in Java! (on second thought, don't hurt
yourself <wink>) (sorry, I am a little annoyed with java right now)
-D