Specify the sorting direction for the various columns/

Mike Kazantsev mk.fraggod at gmail.com
Fri Jun 12 01:34:34 EDT 2009

On Thu, 11 Jun 2009 18:54:56 -0700 (PDT)
Oni <drentha at gmail.com> 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
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,

  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
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 205 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20090612/a6df9634/attachment-0001.sig>

More information about the Python-list mailing list