CODE: Generic Sort Routine

Kamilche klachemin at home.com
Thu Aug 19 04:32:10 EDT 2004


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



More information about the Python-list mailing list