On Thu, 11 Jun 2009 18:54:56 -0700 (PDT) Oni <[email protected]> wrote:
> 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.
...
> bob = entries
> bob.sort(key=operator.itemgetter(*sortorderarr),reverse=True)
> pp.pprint(bob)
Note that this accomplishes nothing, since bob and entries are the same
object, so entries.sort and bob.sort are the same method of the same
object.
You can use "copy" module to clone list and it's contents (dict objects)
or just use list constructor to clone list structure only, leaving
contents essencially the same, but in different order.
Or, in this case, you can just use "sorted" function which constructs
sorted list from any iterable.
As for the question, in addition to Mark's suggestion of doing
sub-sorting, you can also construct complex index (code below).
Dunno which would be more efficient in the particular case...
import datetime
import pprint
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)}]
entries.sort(lambda x: (x['name'], -time.mktime(x['date'].timetuple())))
Here time is inversed, yielding reverse sort order by that column.
--
Mike Kazantsev // fraggod.net
signature.asc
Description: PGP signature
-- http://mail.python.org/mailman/listinfo/python-list
