CODE: Generic Sort Routine

K

Kamilche

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()
 
A

Andrew Henshaw

Kamilche said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top