473,503 Members | 1,635 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Secondary list sorting comparison expression

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

Jul 18 '05 #1
1 2189
[David Pratt]
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.
The simplest approach is to rely on Python's sort being stable. First sort on
the tertiary key, then do another sort on the secondary key, and then sort on
the primary key.

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


Another way is to build out the sort_by_key function to handle multiple fields:

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

In Py2.4, the key= option offers an alternative to cmp which is simpler and
faster:

def sort_by_key(list, i, j, k):
list.sort(key = lambda a : (a[i], a[j], a[k]))
Raymond Hettinger
Jul 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
3235
by: Federico G. Babelis | last post by:
Hi All: I have this line of code, but the syntax check in VB.NET 2003 and also in VB.NET 2005 Beta 2 shows as unknown: Dim local4 As Byte Fixed(local4 = AddressOf dest(offset)) ...
22
4115
by: mike | last post by:
If I had a date in the format "01-Jan-05" it does not sort properly with my sort routine: function compareDate(a,b) { var date_a = new Date(a); var date_b = new Date(b); if (date_a < date_b)...
16
3361
by: aruna | last post by:
Given a set of integers, how to write a program in C to sort these set of integers using C, given the following conditions a. Do not use arrays b. Do not use any comparison function like if/then...
22
5228
by: greenflame | last post by:
I would like to make a function that takes a list, more specificaly a list of strings, and shuffles its elements, like a pile of cards. The following is a script I tryed to make that implements...
3
2143
by: ASP Developer | last post by:
I have a generic list of objects. These objects have a text field that contains a letter for the first character and numbers for the next three. For example, "A001". I need to sort these by...
7
2173
by: apotheos | last post by:
I can't seem to get this nailed down and I thought I'd toss it out there as, by gosh, its got to be something simple I'm missing. I have two different database tables of events that use different...
3
4132
by: tshad | last post by:
I have dataGrid that I am filling from a List Collection and need to sort it by the various columns. So I need to be able to sort the Collection and found that you have to set up your own...
11
163
by: Jon Skeet [C# MVP] | last post by:
Peter Duniho <NpOeStPeAdM@nnowslpianmk.comwrote: Could you give an example of what you mean? I'll try to work out what's going on and whether there's a way round it. Enumerable.OrderBy is...
0
1484
by: Chris Rebert | last post by:
On Wed, Sep 24, 2008 at 2:02 PM, David Di Biase <dave.dibiase@gmail.comwrote: You'd probably be better off using the 'key' keyword argument to ..sort(), which is made for the Schwartzian...
0
7202
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7280
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7332
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6991
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7462
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5578
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5014
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3167
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
382
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.