Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 286429
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T05:38:08+00:00 2026-05-12T05:38:08+00:00

Or, practically, how can I sort a list of dictionaries by multiple keys? I

  • 0

Or, practically, how can I sort a list of dictionaries by multiple keys?

I have a list of dicts:

b = [{u'TOT_PTS_Misc': u'Utley, Alex', u'Total_Points': 96.0},
 {u'TOT_PTS_Misc': u'Russo, Brandon', u'Total_Points': 96.0},
 {u'TOT_PTS_Misc': u'Chappell, Justin', u'Total_Points': 96.0},
 {u'TOT_PTS_Misc': u'Foster, Toney', u'Total_Points': 80.0},
 {u'TOT_PTS_Misc': u'Lawson, Roman', u'Total_Points': 80.0},
 {u'TOT_PTS_Misc': u'Lempke, Sam', u'Total_Points': 80.0},
 {u'TOT_PTS_Misc': u'Gnezda, Alex', u'Total_Points': 78.0},
 {u'TOT_PTS_Misc': u'Kirks, Damien', u'Total_Points': 78.0},
 {u'TOT_PTS_Misc': u'Worden, Tom', u'Total_Points': 78.0},
 {u'TOT_PTS_Misc': u'Korecz, Mike', u'Total_Points': 78.0},
 {u'TOT_PTS_Misc': u'Swartz, Brian', u'Total_Points': 66.0},
 {u'TOT_PTS_Misc': u'Burgess, Randy', u'Total_Points': 66.0},
 {u'TOT_PTS_Misc': u'Smugala, Ryan', u'Total_Points': 66.0},
 {u'TOT_PTS_Misc': u'Harmon, Gary', u'Total_Points': 66.0},
 {u'TOT_PTS_Misc': u'Blasinsky, Scott', u'Total_Points': 60.0},
 {u'TOT_PTS_Misc': u'Carter III, Laymon', u'Total_Points': 60.0},
 {u'TOT_PTS_Misc': u'Coleman, Johnathan', u'Total_Points': 60.0},
 {u'TOT_PTS_Misc': u'Venditti, Nick', u'Total_Points': 60.0},
 {u'TOT_PTS_Misc': u'Blackwell, Devon', u'Total_Points': 60.0},
 {u'TOT_PTS_Misc': u'Kovach, Alex', u'Total_Points': 60.0},
 {u'TOT_PTS_Misc': u'Bolden, Antonio', u'Total_Points': 60.0},
 {u'TOT_PTS_Misc': u'Smith, Ryan', u'Total_Points': 60.0}]

and I need to use a multi key sort reversed by Total_Points, then not reversed by TOT_PTS_Misc.

This can be done at the command prompt like so:

a = sorted(b, key=lambda d: (-d['Total_Points'], d['TOT_PTS_Misc']))

But I have to run this through a function, where I pass in the list and the sort keys. For example, def multikeysort(dict_list, sortkeys):.

How can the lambda line be used which will sort the list, for an arbitrary number of keys that are passed in to the multikeysort function, and take into consideration that the sortkeys may have any number of keys and those that need reversed sorts will be identified with a ‘-‘ before it?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T05:38:09+00:00Added an answer on May 12, 2026 at 5:38 am

    This answer works for any kind of column in the dictionary — the negated column need not be a number.

    def multikeysort(items, columns):
        from operator import itemgetter
        comparers = [((itemgetter(col[1:].strip()), -1) if col.startswith('-') else
                      (itemgetter(col.strip()), 1)) for col in columns]
        def comparer(left, right):
            for fn, mult in comparers:
                result = cmp(fn(left), fn(right))
                if result:
                    return mult * result
            else:
                return 0
        return sorted(items, cmp=comparer)
    

    You can call it like this:

    b = [{u'TOT_PTS_Misc': u'Utley, Alex', u'Total_Points': 96.0},
         {u'TOT_PTS_Misc': u'Russo, Brandon', u'Total_Points': 96.0},
         {u'TOT_PTS_Misc': u'Chappell, Justin', u'Total_Points': 96.0},
         {u'TOT_PTS_Misc': u'Foster, Toney', u'Total_Points': 80.0},
         {u'TOT_PTS_Misc': u'Lawson, Roman', u'Total_Points': 80.0},
         {u'TOT_PTS_Misc': u'Lempke, Sam', u'Total_Points': 80.0},
         {u'TOT_PTS_Misc': u'Gnezda, Alex', u'Total_Points': 78.0},
         {u'TOT_PTS_Misc': u'Kirks, Damien', u'Total_Points': 78.0},
         {u'TOT_PTS_Misc': u'Worden, Tom', u'Total_Points': 78.0},
         {u'TOT_PTS_Misc': u'Korecz, Mike', u'Total_Points': 78.0},
         {u'TOT_PTS_Misc': u'Swartz, Brian', u'Total_Points': 66.0},
         {u'TOT_PTS_Misc': u'Burgess, Randy', u'Total_Points': 66.0},
         {u'TOT_PTS_Misc': u'Smugala, Ryan', u'Total_Points': 66.0},
         {u'TOT_PTS_Misc': u'Harmon, Gary', u'Total_Points': 66.0},
         {u'TOT_PTS_Misc': u'Blasinsky, Scott', u'Total_Points': 60.0},
         {u'TOT_PTS_Misc': u'Carter III, Laymon', u'Total_Points': 60.0},
         {u'TOT_PTS_Misc': u'Coleman, Johnathan', u'Total_Points': 60.0},
         {u'TOT_PTS_Misc': u'Venditti, Nick', u'Total_Points': 60.0},
         {u'TOT_PTS_Misc': u'Blackwell, Devon', u'Total_Points': 60.0},
         {u'TOT_PTS_Misc': u'Kovach, Alex', u'Total_Points': 60.0},
         {u'TOT_PTS_Misc': u'Bolden, Antonio', u'Total_Points': 60.0},
         {u'TOT_PTS_Misc': u'Smith, Ryan', u'Total_Points': 60.0}]
    
    a = multikeysort(b, ['-Total_Points', 'TOT_PTS_Misc'])
    for item in a:
        print item
    

    Try it with either column negated. You will see the sort order reverse.

    Next: change it so it does not use extra class….


    2016-01-17

    Taking my inspiration from this answer What is the best way to get the first item from an iterable matching a condition?, I shortened the code:

    from operator import itemgetter as i
    
    def multikeysort(items, columns):
        comparers = [
            ((i(col[1:].strip()), -1) if col.startswith('-') else (i(col.strip()), 1))
            for col in columns
        ]
        def comparer(left, right):
            comparer_iter = (
                cmp(fn(left), fn(right)) * mult
                for fn, mult in comparers
            )
            return next((result for result in comparer_iter if result), 0)
        return sorted(items, cmp=comparer)
    

    In case you like your code terse.


    Later 2016-01-17

    This works with python3 (which eliminated the cmp argument to sort):

    from operator import itemgetter as i
    from functools import cmp_to_key
    
    def cmp(x, y):
        """
        Replacement for built-in function cmp that was removed in Python 3
    
        Compare the two objects x and y and return an integer according to
        the outcome. The return value is negative if x < y, zero if x == y
        and strictly positive if x > y.
    
        https://portingguide.readthedocs.io/en/latest/comparisons.html#the-cmp-function
        """
    
        return (x > y) - (x < y)
    
    def multikeysort(items, columns):
        comparers = [
            ((i(col[1:].strip()), -1) if col.startswith('-') else (i(col.strip()), 1))
            for col in columns
        ]
        def comparer(left, right):
            comparer_iter = (
                cmp(fn(left), fn(right)) * mult
                for fn, mult in comparers
            )
            return next((result for result in comparer_iter if result), 0)
        return sorted(items, key=cmp_to_key(comparer))
    

    Inspired by this answer How should I do custom sort in Python 3?

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Why should I use JSON with ASP.NET? Can you give a practical example? I
OK, so practically every database based application has to deal with non-active records. Either,
I need to parse a xml file which is practically an image of a
Inside my code I'm generating hashes of URLs, (which are practically of unbounded length).
Does anyone have any practical suggestions about how to manage feature creep in GUIs?
After reading Practical Common Lisp I finally understood what the big deal about macros
What is your best practical user-friendly user-interface design or principle? Please submit those practices
What is the practical benefit of using HTTP GET, PUT, DELETE, POST, HEAD? Why
What are some practical uses for the Curiously Recurring Template Pattern ? The counted
Not too practical maybe, but still interesting. Having some abstract question on matrix multiplication

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.