[Tutor] Sorting Data

Jeff Shannon jeff@ccvcorp.com
Mon, 19 Aug 2002 12:48:45 -0700


Alan Colburn wrote:

> What's a typical way to be able to sort the database by any list element?

This depends to some degree on the size of the database.  If you have anything
more than a few hundred records, you should probably use some sort of dbms
that's more reliable than simply lists or dictionaries.  However, if your needs
are small, lists will work fairly well.

What you need to do to sort your list, is to create a *new* list.  Each element
of the new list will be a tuple of two values -- the first one is the contents
of the column you want to sort on, the second one is the *entire* record
(sublist) from the original list.  You can then sort the new list, and lastly
pull the records into *another* list in their new order.

Some quick (untested) code, using list comprehensions:

def SortByColumn(outerlist, column):
    temp = [ (record[column], record) for record in outerlist ]
    temp.sort()
    sortedlist = [record[1] for record in temp]
    return sortedlist

This is sometimes known as the "decorate-sort-undecorate" pattern, because
you're "decorating" the original list with the contents of the column that you
want to sort on.

Jeff Shannon
Technician/Programmer
Credit International