[Python] How to sort objects by multiple keys?

Discussão em 'Python' iniciado por Stack, Agosto 1, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página