This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author cykerway
Recipients cykerway
Date 2018-10-17.10:10:40
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1539771040.54.0.788709270274.issue35010@psf.upfronthosting.co.za>
In-reply-to
Content
The current `sorted` function is somewhat limited and doesn't cover a use case that frequently occurs in real applications: sort by a tuple of keys where each key can be in asc or desc order.

For example, you may have a list of site configs where each of specify which user on which site gets how much quota. This data may be loaded from a SQL table where there are 3 columns: url, user, quota. Often you may want to sort by url, but when you want to check which users have been allocated most quota, you probably want to sort by quota. Even more likely, when you are sorting by quota, you still want to sort by url for those having the same quota.

Unfortunately, current `sorted` function doesn't allow you to sort by desc quota and asc url at the same time, because the `reverse` parameter acts on the final result, regardless of columns. For numeric columns, there is a trick of using minus sign on the data. But this approach usually doesn't apply to other types of data.

The general solution is to enhance the key function, allowing users to specify each column to be considered, with an asc/desc flag:

    keyspec = [
        (itemgetter('url'), False),
        (itemgetter('user'), True),
    ]

An example is worth 1k words. The full example is provided in the attachment.

It's not a lot of code to write but making this feature builtin can save a lot of work since sorting a SQL table or other sheet data is quite common in real applications.
History
Date User Action Args
2018-10-17 10:10:40cykerwaysetrecipients: + cykerway
2018-10-17 10:10:40cykerwaysetmessageid: <1539771040.54.0.788709270274.issue35010@psf.upfronthosting.co.za>
2018-10-17 10:10:40cykerwaylinkissue35010 messages
2018-10-17 10:10:40cykerwaycreate