Specify the sorting direction for the various columns/

Oni drentha at gmail.com
Fri Jun 12 03:54:56 CEST 2009


Managed to get a dictionary to sort on multiple columns using a tuple
to set the sort order (see below). However how can I control that
column "date" orders descending and the column "name" orders
ascending.

Thanks

import datetime
import pprint
import operator

faUserFormInput = {'DDPageSortOrder': 'PageAge'}
mypages = ["PageName","PageAge","PageAge"]

gaValidSortOrder = [
            {'OrderType': 'PageName',   'SortOrder': ('name')},
            {'OrderType': 'PageAge',    'SortOrder': ('date','name')},
            {'OrderType': 'PageAuthor', 'SortOrder':
('username','date')}
        ]

entries = [{'name': 'ZZ2', 'username': 'ZZ3', 'date': datetime.datetime
(2008, 9, 30, 16, 43, 54)},{'name': 'ZZ2', 'username': 'ZZ5','date':
datetime.datetime(2008, 9, 30, 16, 43, 54)},{'name': 'ZZ2',
'username': 'ZZ1', 'date': datetime.datetime(2007, 9, 30, 16, 43, 54)},
{'name': 'AA2', 'username': 'AA2','date': datetime.datetime(2007, 9,
30, 16, 43, 54)}]

sortorderarr = ('name','date')

#if ("DDPageSortOrder" in faUserFormInput):
for item in gaValidSortOrder:
    print "1=%s" % (item["OrderType"])
    print "2=%s" % (faUserFormInput["DDPageSortOrder"])
    if (item["OrderType"] == faUserFormInput["DDPageSortOrder"]):
        sortorderarr = item["SortOrder"]
        #sortorderarr = '\','.join(sortorder)
        print sortorderarr

pp = pprint.PrettyPrinter(depth=2)
pp.pprint(entries)

bob = entries
bob.sort(key=operator.itemgetter(*sortorderarr),reverse=True)
pp.pprint(bob)



More information about the Python-list mailing list