Secondary list sorting comparison expression

David Pratt fairwinds at eastlink.ca
Tue Mar 8 20:08:24 CET 2005


I have been using the following for sorting a list of dictionaries.  
This works but only provides sorting on a single key.  I am wanting to 
extend this with a better comparison expression so that it would sort 
on one key as primary, a second key as secondary sort , and maybe even 
a third as tertiary.

def sort_by_key(list, i):
       list.sort(lambda a, b: cmp(a[i], b[i]))

test_list = [{'number': 1, 'written_number': 'one','animal': 
'giraffe','price': 1.50},  {'number': 2, 'written_number': 
'two','animal': 'elephant', 'price': 2.50}, {'number': 3, 
'written_number': 'three','animal': 'zebra', 'price': 1.50}, {'number': 
4, 'written_number': 'four','animal': 'hippopotamus', 'price': 1.50}]

sort_by_key(test_list, 'price')

This returns:
[{'price': 1.5, 'number': 1, 'animal': 'giraffe', 'written_number': 
'one'}, {'price': 1.5, 'number': 3, 'animal': 'zebra', 
'written_number': 'three'}, {'price': 1.5, 'number': 4, 'animal': 
'hippopotamus', 'written_number': 'four'}, {'price': 2.5, 'number': 2, 
'animal': 'elephant', 'written_number': 'two'}]

What I am looking for would sort on more than one key so, say 'price' 
and 'animal' so that the list would be ordered with the three items at 
1.50 each but records would be giraffe, hippopotamus and zebra.  If I 
wanted to sort on three indexes, say 'price', 'animal' and 'written 
number' and say last two animals were both zebras that it would put 
this in the correct order also.

I am have to say I have read a good deal about sorting today but have 
not come across a solution and have seen only limited comparison 
expressions to know what could work.

Regards,
David




More information about the Python-list mailing list