This article has a nice rundown on various techniques for doing this. If your requirements are simpler than "full bidirectional multikey", take a look. It's clear the accepted answer and the blog post I just referenced influenced each other in some way, though I don't know which order.

In case the link dies here's a very quick synopsis of examples not covered above:

from operator import itemgetter

mylist = sorted(mylist, key=itemgetter('name', 'age'))
mylist = sorted(mylist, key=lambda k: (k['name'].lower(), k['age']))
mylist = sorted(mylist, key=lambda k: (k['name'].lower(), -k['age']))
Answer from Scott Stafford on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › sort-list-of-dictionaries-python-by-multiple-keys
Sort List of Dictionaries by Multiple Keys - Python - GeeksforGeeks
July 23, 2025 - sorted() function is a built-in Python function that sorts any iterable and returns a new sorted list. It can be used with a custom sorting key to sort dictionaries based on multiple keys.
Top answer
1 of 9
130

This article has a nice rundown on various techniques for doing this. If your requirements are simpler than "full bidirectional multikey", take a look. It's clear the accepted answer and the blog post I just referenced influenced each other in some way, though I don't know which order.

In case the link dies here's a very quick synopsis of examples not covered above:

from operator import itemgetter

mylist = sorted(mylist, key=itemgetter('name', 'age'))
mylist = sorted(mylist, key=lambda k: (k['name'].lower(), k['age']))
mylist = sorted(mylist, key=lambda k: (k['name'].lower(), -k['age']))
2 of 9
94

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?

🌐
Reddit
reddit.com › r/askprogramming › help with python function to sort a list of dictionaries by multiple keys
r/AskProgramming on Reddit: Help with Python function to sort a list of dictionaries by multiple keys
July 11, 2025 -

I'm trying to write a Python function that sorts a list of dictionaries by multiple keys, but I keep running into issues with the ordering and index positions. Here's an example of what I'm working with:

```

[

{"name": "John", "age": 30, "city": "New York"},

{"name": "Alice", "age": 25, "city": "Chicago"},

{"name": "Bob", "age": 40, "city": "San Francisco"}

]

```

I want to sort this list by "name" first, and then by "age". However, when I use the `sorted()` function with a custom key, it seems to be treating all keys as if they were equal. For example, if I'm sorting by "name" and "age", but there are duplicates in "name" (e.g. two people named "Alice"), it will treat those as if they're equal.

Does anyone know of a way to achieve this in Python? Or is there a better data structure I should be using for this type of task?

I've tried using the `sorted()` function with a custom key, but like I said, it doesn't seem to work as expected. I've also looked into using `numpy` or `pandas`, but those seem to overcomplicate things for what I need.

Edit: I've been experimenting with different sorting methods, and I've come across a solution that uses the `functools.cmp_to_key()` function to convert my comparison function to a key function. However, I'm still having issues with getting the desired output.

🌐
30 Seconds of Code
30secondsofcode.org › home › dictionary › sort dictionary list using a tuple key
Sort Python dictionary list using a tuple key - 30 seconds of code
January 4, 2023 - Luckily, the sorted() function can be used to sort a list of dictionaries using a tuple key. Simply return a tuple with the order of keys you want to sort by and the sorted() function will do the rest.
🌐
Reddit
reddit.com › r/learnpython › how to sort a dictionary where keys have multiple values?
r/learnpython on Reddit: How to sort a dictionary where keys have multiple values?
December 12, 2018 -

So say this is my dictionary: {'John Adams': ('111223333', 'A', 91.0), 'Willy Smith Jr.': ('222114444', 'C', 77.55), 'Phil Jordan': ('777886666', 'F', 59.5)} and i want to sort it by the third value of each key (eg the 91.0 for John Adams). How would I go about doing that?

Top answer
1 of 4
8

Use a lambda as your sort function.

# lambda r: r[1][2]
# r == ('John Adams', ('111223333', 'A', 91.0))
# r[1] == ('111223333', 'A', 91.0)
# r[1][2] == 91.0
#
d = {
    'John Adams': ('111223333', 'A', 91.0),
    'Willy Smith Jr.': ('222114444', 'C', 77.55),
    'Phil Jordan': ('777886666', 'F', 59.5)
}

for key, value in sorted(d.items(), key=lambda r: r[1][2]):
    print(key, value)

Produces:

('Phil Jordan', ('777886666', 'F', 59.5))
('Willy Smith Jr.', ('222114444', 'C', 77.55))
('John Adams', ('111223333', 'A', 91.0))

By the way, if you end up with multiple entries sharing the same sort value, you can build a compound sort (secondary, tertiary, etc). Your lambda should just return a tuple: lambda r: (r[1][2], r[0]), which would sort by that last value, and then by name if multiple values equal each other.

Here's without lambda:

def key_func(key_value_tuple):
    name = key_value_tuple[0]
    long_str_num, a_to_f, number = key_value_tuple[1]
    return (number, name)

d = {
    'John Adams': ('111223333', 'A', 91.0),
    'Willy Smith Jr.': ('222114444', 'C', 77.55),
    'Phil Jordan': ('777886666', 'F', 59.5)
}

for key, value in sorted(d.items(), key=key_func):
    print(key, value)

Edit: Added non-lambda option.

2 of 4
5

Here's an extension of u/totallygeek's non-lambda solution, using a more advanced Python feature:

d = {'John Adams': ('111223333', 'A', 91.0), 'Willy Smith Jr.': ('222114444', 'C', 77.55),
     'Phil Jordan': ('777886666', 'F', 59.5)}

def sortindex(index):
    def key_func(item):
        key, value = item
        return (value[index], key)
    return key_func

for key, value in sorted(d.items(), key=sortindex(2)):
    print(key, value)

Here, key_func is wrapped inside another function, sortindex, which returns key_func. In other words, the code above does the same thing as this

def key_func(item):
    key, value = item
    return (value[2], key)

for key, value in sorted(d.items(), key=key_func):
    print(key, value)

But notice that the sortindex function allows us to keep the tuple index as a free variable, so that we can also sort on sortindex(0) or sortindex(1).

This technique of wrapping one function inside another is called a closure.

🌐
Note.nkmk.me
note.nkmk.me › home › python
Sort a List of Dictionaries by the Value of the Specific Key in Python | note.nkmk.me
May 14, 2023 - In Python, sorting a list of ... (TypeError) by default. By specifying the key argument of sort() or sorted(), you can sort a list of dictionaries according to the value of the specific key....
🌐
Real Python
realpython.com › sort-python-dictionary
Sorting a Python Dictionary: Values, Keys, and More – Real Python
December 14, 2024 - In the following code, you’ll be using timeit to compare the time it takes to sort the two data structures by the age attribute: Language: Python Filename: compare_sorting_dict_vs_list.py · from timeit import timeit from samples import dictionary_of_dictionaries, list_of_dictionaries sorting_list = "sorted(list_of_dictionaries, key=lambda item:item['age'])" sorting_dict = """ dict( sorted( dictionary_of_dictionaries.items(), key=lambda item: item[1]['age'] ) ) """ sorting_list_time = timeit(stmt=sorting_list, globals=globals()) sorting_dict_time = timeit(stmt=sorting_dict, globals=globals()) print( f"""\ {sorting_list_time=:.2f} seconds {sorting_dict_time=:.2f} seconds list is {(sorting_dict_time/sorting_list_time):.2f} times faster""" )
🌐
Finxter
blog.finxter.com › home › learn python blog › efficient strategies to sort a list of dictionaries by multiple keys in python
Efficient Strategies to Sort a List of Dictionaries by Multiple Keys in Python - Be on the Right Side of Change
February 22, 2024 - For example, given a list of employee ... to sort a list of dictionaries by multiple keys is to use the sorted() function combined with a lambda function to specify the keys....
Find elsewhere
🌐
freeCodeCamp
freecodecamp.org › news › python-sort-dictionary-by-key
Python Sort Dictionary by Key – How to Sort a Dict with Keys
May 25, 2023 - The simplest way to sort a dictionary by its keys is by using the sorted() function along with the items() method of the dictionary. The items() method returns a list of key-value pairs as tuples.
🌐
Medium
medium.com › @python-javascript-php-html-css › sorting-a-list-of-dictionaries-in-python-by-a-specific-key-0e93fa7ffff1
Using a Specific Key to Sort a List of Dictionaries in Python | by Denis Bélanger 💎⚡✨ | Medium
August 24, 2024 - You can sort a list of dictionaries in descending order by using the reverse=True parameter with the sorted() or sort() function. ... Yes, you can sort by multiple keys by using a key parameter that returns a tuple of values to sort by, e.g., ...
🌐
Finxter
blog.finxter.com › home › learn python blog › python – how to sort a list of dictionaries?
Python - How to Sort a List of Dictionaries? - Be on the Right Side of Change
April 8, 2020 - In this article, you’ll learn the ins and outs of the sorting function in Python. In particular, you’re going to learn how to sort a list of dictionaries in all possible variations. [1] So let’s get started! ... Problem: Given a list of dictionaries. Each dictionary consists of multiple (key, value) pairs. You want to sort them by value of a particular dictionary key (attribute).
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › ways-sort-list-dictionaries-values-python-using-itemgetter
Ways to sort list of dictionaries by values in Python – Using itemgetter - GeeksforGeeks
November 6, 2025 - from operator import itemgetter d = [ {"name": "Nandini", "age": 20}, {"name": "Manjeet", "age": 20}, {"name": "Nikhil", "age": 19} ] print("Sorted by age (descending): ", sorted(d, key=itemgetter('age'), reverse=True)) ... Sorted by age (descending): [{'name': 'Nandini', 'age': 20}, {'name': 'Manjeet', 'age': 20}, {'name': 'Nikhil', 'age': 19}] Ways to sort list of dictionaries by values in Python - Using lambda function · Sort List of Dictionaries by Multiple Keys - Python
🌐
Reddit
reddit.com › r/maildevnetwork › sorting a list of dictionaries in python by a specific key
r/MailDevNetwork on Reddit: Sorting a List of Dictionaries in Python by a Specific Key
July 17, 2024 - You can sort a list of dictionaries in descending order by using the reverse=True parameter with the sorted() or sort() function. ... Yes, you can sort by multiple keys by using a key parameter that returns a tuple of values to sort by, e.g., ...
🌐
GitHub
gist.github.com › malero › 418204
python-sort-list-object-dictionary-multiple-key.1.py · GitHub
Keyword Arguments: items -- A list of dictionary objects or objects columns -- A list of column names to sort by. Use -column to sort in descending order functions -- A Dictionary of Column Name -> Functions to normalize or process each column value getter -- Default "getter" if column function does not exist operator.itemgetter for Dictionaries operator.attrgetter for Objects """ comparers = [] for col in columns: column = col[1:] if col.startswith('-') else col if not column in functions: functions[column] = getter(column) comparers.append((functions[column], 1 if column == col else -1)) def
🌐
YouTube
youtube.com › watch
How to Sort a List of Dictionaries by Multiple Keys in Python - YouTube
Learn how to efficiently sort a list of dictionaries in Python by one key in ascending order and another key in descending order.---This video is based on th...
Published   October 8, 2025
Views   0
🌐
Reddit
reddit.com › r/learnpython › how to sort a list containing dictionary items?
r/learnpython on Reddit: How to sort a list containing dictionary items?
September 30, 2023 -

Let's say i have a list from a json like this:

list = [
{
    "name": "Player1",
    "currency": "10"
},
{
    "name": "Player2",
    "currency": "15"
},
    {
    "name": "Player3",
    "currency": "7"
}

]

How do i sort it based on the amount of currency a player has so that i can get the richest players using simple list indexes? For example if i want the details of the second richest player, i sort the list based on the amount of currency player has and then do a simple list[1] to get their details. How do i achieve this?

Top answer
1 of 4
5
List objects have a sort function to sort the list in-place. This function has a key parameter to specify a function that will be called on each item in the list, after which the items will be sorted based on the results of that function. It also accepts a reverse parameter that, if set to True, will cause sort to sort the list in descending order. Let's say you have a list students that contains Student objects. To sort the students by age from oldest to youngest, you'd do students.sort(key = lambda x: x.Age, reverse=True). Sorting your list of dictionaries is done in pretty much the same way. See this if you need more examples. Keep in mind that in your list, the currency values are strings, not integers. You'll need to convert them first, otherwise they won't be sorted correctly. You can do that in the lambda function you pass to sort. Incidentally, using variable names like list is bad practice. You're overriding the built-in list class by doing that.
2 of 4
2
list_ = [ { "name": "Player1", "currency": "10" }, { "name": "Player2", "currency": "15" }, { "name": "Player3", "currency": "7" } ] new_list_ = sorted(list_, key=lambda x: int(x["currency"])) print(new_list_) NB. Strongly recommend against using Python types/names for variable names, as it makes it harder to access original features. Hence, appended _ to list from your example. new_list_[-2] will reference the second-richest player (well, not if they have matching currency levels. If you want that, you will need to collect the unique values, find the second highest, and then find the players with that amount. Note, sorted can use the reversed keyword. PS. Example to find second richest, amounts = sorted(set(int(x['currency']) for x in new_list_)) if len(amounts) > 1: second_highest = amounts[-2] print(f"{second_highest=}") for player in new_list_: if int(player['currency']) == second_highest: print(player["name"]) else: print("No player is second richest") NB. Might be easier to convert the currency values to numbers before doing anything else.
🌐
LabEx
labex.io › tutorials › python-how-to-sort-a-list-of-dictionaries-by-a-key-in-python-398246
How to sort a list of dictionaries by a key in Python | LabEx
Another way to sort a list of dictionaries is by using the itemgetter() function from the operator module. This approach is particularly useful when you need to sort by multiple keys.
🌐
Medium
medium.com › @vipinc.007 › python-sort-a-list-of-dictionaries-by-key-d9347f592b2f
Python | sort a list of dictionaries by key | by Vipin Cheriyanveetil | Medium
February 21, 2023 - By using the sorted() function and a key function, we can easily sort the list in ascending or descending order based on any key of the dictionaries. ... Full Stack Developer: Python, React, Node.js, Neo4j (vipinc.007@gmail.com) https://bud...