473,503 Members | 11,435 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

CODE: Generic Sort Routine

I've written a generic sort routine that will sort dictionaries,
lists, or tuples, either by a specified key or by value.

Comments welcome!

import types

def sort(container, key = None, ascending = True):
' Sort lists or dictionaries by the specified key'
t = type(container)
if t in (types.ListType, types.TupleType):
thelist = container
else:
thelist = container.values()
if key:
sorted = zip([getattr(item, key) for item in thelist],
thelist)
else:
sorted = list(thelist)
sorted.sort()
if ascending == False:
sorted.reverse()
if key:
return [x[1] for x in sorted]
else:
return sorted

class simple:
name = 'simple'
def __init__(self, word):
self.word = word
def __repr__(self):
return str(self.__dict__)

def test():
# Set up the test data
line = 'now is the time for all good men to come to the aid of
their country.'
words = line.split(' ')
compareto = line.split(' ')
compareto.sort()
assert words != compareto
objects = []
for word in words:
o = simple(word)
objects.append(o)

# Sort a list of words
test1 = sort(words)
assert test1 == compareto

# Sort a list of objects
lst = sort(objects, 'word')
test2 = []
for item in lst:
test2.append(item.word)
assert(test2 == compareto)

# Sort a tuple of objects
tup = tuple(objects)
lst = sort(tup, 'word')
test3 = []
for item in lst:
test3.append(item.word)
assert(test3 == compareto)

# Sort a dict of objects
d = {}
ctr = 1
for item in objects:
d[ctr] = item
ctr += 1
lst = sort(d, 'word')
test4 = []
for item in lst:
test4.append(item.word)
assert(test4 == compareto)

# Reverse sort a dict of objects
d = {}
ctr = 1
for item in objects:
d[ctr] = item
ctr += 1
lst = sort(d, 'word', False)
test4 = []
for item in lst:
test4.append(item.word)
compareto.reverse()
assert(test4 == compareto)

# Sort a list of numbers
lst = [5, 9, 3, 54, 6, 65.7, 2.4, 9999]
lst = sort(lst)
print lst

# Done
print "All tests passed!"

if __name__ == "__main__":
test()
Jul 18 '05 #1
1 2268
Kamilche wrote:
I've written a generic sort routine that will sort dictionaries,
lists, or tuples, either by a specified key or by value.

Comments welcome!
....snip... if key:
sorted = zip([getattr(item, key) for item in thelist],
thelist)
else:
sorted = list(thelist)

....snip...

I'd change that 'if key:' line to 'if key is not None:', so that you could
sort on other non-True values.

Andy
Jul 18 '05 #2

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

Similar topics

242
13122
by: James Cameron | last post by:
Hi I'm developing a program and the client is worried about future reuse of the code. Say 5, 10, 15 years down the road. This will be a major factor in selecting the development language. Any...
40
4218
by: Elijah Bailey | last post by:
I want to sort a set of records using STL's sort() function, but dont see an easy way to do it. I have a char *data; which has size mn bytes where m is size of the record and n is the...
3
1738
by: Mel | last post by:
i need to sort my table based on a "header click". is there a generic code out there that does that for me, or i have to write one for each and every table i come up with ? many thanks for...
65
12505
by: Skybuck Flying | last post by:
Hi, I needed a method to determine if a point was on a line segment in 2D. So I googled for some help and so far I have evaluated two methods. The first method was only a formula, the second...
4
1243
by: ITnerd | last post by:
In the interest of code re-use, I would like to place some code in a utility class to be used by other classes. The problem is that this code requires the following snippet: for(i=0; i <...
3
1623
by: dhussong | last post by:
I'm trying to implement a generic exception handling routine that will write information to a text file at the time the exception occurred. I am using the Microsoft Application Block for Exception...
0
1050
by: Roger Twomey | last post by:
I am writing a Windows service which is run (and tested) at a remote location so I cannot debug issues at the actual deployment site. I know that the application is having some sort of trouble as...
239
10024
by: Eigenvector | last post by:
My question is more generic, but it involves what I consider ANSI standard C and portability. I happen to be a system admin for multiple platforms and as such a lot of the applications that my...
1
3888
by: raylopez99 | last post by:
I seem to get name collision between the Generic collection SortedList and C++.NET Framework collection SortedList. How to resolve? Here are the libraries that seem to clash:...
0
7067
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7264
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
7316
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
6975
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...
1
4992
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
3160
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
3148
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
728
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
371
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.