๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ ways-sort-list-dictionaries-values-python-using-lambda-function
Ways to sort list of dictionaries by values in Python - Using lambda function - GeeksforGeeks
November 14, 2025 - ... Explanation: (sorted(dic, key=lambda x: (x['age'], x['name'])): Sorts the list of dictionaries first by "age" in ascending order and if ages are equal then by "name" in alphabetic order.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ sorting with key=lambda
r/learnpython on Reddit: sorting with key=lambda
March 14, 2023 -
pairs= [(1,'one'),(2,'two'),(3,'three'),(4,"four"),(5,"five")]
pairs.sort(key=lambda pair: pair[1])

>>> pairs
[(5, 'five'), (4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

why is it sorted like that I didn't understand? Why can't I write a number greater than 1 in pair[1]?

Discussions

How to sort a dictionary where keys have multiple values?

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.

More on reddit.com
๐ŸŒ r/learnpython
9
10
December 12, 2018
Sorting dictionary by key with lambda: WTF??
key is just a regular argument that the list.sort() function takes. It's not special in any way. It's not a keyword. (It is a keyword-only argument, but that's not the same as being a keyword.) In other words, the list.sort() method specifically expects an argument named key that contains a callback function to be used to control the sort. You can't pass a callback function as an argument to any random old function that isn't expecting it. It also has nothing specifically to do with lambda functions; you could pass a regular function too. (Or you could pass an instance that has __call__() implemented, i.e. any callable.) pair is the name of the parameter of the anonymous function being defined. It's arbitrary; you can name your arguments whatever you want. BTW, I'd argue that that's a bad example and it should be written as import operator ... pairs.sort(key=operator.itemgetter(1)) More on reddit.com
๐ŸŒ r/learnpython
4
1
September 18, 2016
sorting - How to sort a Python dictionary by value? - Stack Overflow
Possible Duplicate: In Python how do I sort a list of dictionaries by values of the dictionary? Sorting Python dictionary based on nested dictionary values I have dictionary of the form as More on stackoverflow.com
๐ŸŒ stackoverflow.com
sorting with key=lambda
pair is a tuple consisting of two items. Index 0 is the first item, index 1 is the second item. There is no other item in the tuple for any other index value to be valid. More on reddit.com
๐ŸŒ r/learnpython
11
1
March 14, 2023
๐ŸŒ
Real Python
realpython.com โ€บ sort-python-dictionary
Sorting a Python Dictionary: Values, Keys, and More โ€“ Real Python
December 14, 2024 - To sort a Python dictionary by its keys, you use the sorted() function combined with .items(). This approach returns a list of tuples sorted by keys, which you can convert back to a dictionary using the dict() constructor. Sorting by values requires specifying a sort key using a lambda function or itemgetter()....
๐ŸŒ
w3resource
w3resource.com โ€บ python-exercises โ€บ lambda โ€บ python-lambda-exercise-4.php
Python: Sort a list of dictionaries using Lambda - w3resource
July 12, 2025 - It uses the sorted() function and a lambda function as the sorting key. Finally, it displays both the original list of dictionaries and the sorted list to the console. ... Write a Python program to sort a list of dictionaries by a given key ...
๐ŸŒ
Runestone Academy
runestone.academy โ€บ ns โ€บ books โ€บ published โ€บ fopp โ€บ Sorting โ€บ SortingaDictionary.html
16.4. Sorting a Dictionary โ€” Foundations of Python Programming
Remember that the key function always takes as input one item from the sequence and returns a property of the item. In our case, the items to be sorted are the dictionaryโ€™s keys, so each item is one key from the dictionary. To remind ourselves of that, weโ€™ve named the parameter in tha lambda expression k.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-sort-python-dictionaries-by-key-or-value
Sort Python Dictionary by Key or Value - Python - GeeksforGeeks
Let's explore different methods to sort dictionary by key or value in Python. 1. Using sorted() with lambda: This method sorts the dictionary efficiently by its values using the sorted() function and a lambda expression.
Published ย  January 13, 2026
Find elsewhere
๐ŸŒ
GoLinuxCloud
golinuxcloud.com โ€บ home โ€บ python โ€บ 10 simple ways to sort dictionary by key in python
10 simple ways to sort dictionary by key in Python | GoLinuxCloud
January 9, 2024 - #!/usr/bin/env python3 mydict_1 ... in the new dict new_dict[key] = value print(new_dict) ... The lambda statement in Python is simply an anonymous function....
๐ŸŒ
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 - Sort a list, string, tuple in Python (sort, sorted) As shown above, an error is raised if the specified key does not exist. # sorted(l, key=lambda x: x['Point']) # KeyError: 'Point' ... In such a case, use the get() method of dict, which returns the default value for non-existent keys. Get value from dictionary by key with get() in Python
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ python sort dictionary by key
Python Sort Dictionary by Key - Spark By {Examples}
May 31, 2024 - Pass the items() function and lambda function into the sorted() function, it will sort the dictionary by keys and finally, get the sorted dictionary by keys using the dict() function.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ ways-to-sort-list-of-dictionaries-by-values-in-python-using-lambda-function
Ways to sort list of dictionaries by values in Python Using lambda function
When it is required to sort the list of dictionaries based on values, the lambda function can be used. ... from operator import itemgetter my_list = [{ "name" : "Will", "age" : 56}, { "name" : "Rob", "age" : 20 }, { "name" : "Mark" , "age" : 34 }, { "name" : "John" , "age" : 24 }] print("The ...
๐ŸŒ
Bacancy Technology
bacancytechnology.com โ€บ qanda โ€บ python โ€บ use-lambda-for-sorting-in-python
How to Use Lambda for Sorting in Python: A Quick Guide
January 20, 2025 - data = [ {'name': 'John', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 22} ] # Sort by 'age' using lambda function sorted_data = sorted(data, key=lambda x: x['age']) print(sorted_data); ... lambda x: x[โ€˜ageโ€™] is used ...
๐ŸŒ
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.

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ sorting dictionary by key with lambda: wtf??
r/learnpython on Reddit: Sorting dictionary by key with lambda: WTF??
September 18, 2016 -

Hi,

going through the python.org tutorial. Came across this example:

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

Ran it through pythontutor, and what i can see is that

  1. the lambda function returns the second element of each tuple.

  2. the dictionary is then sorted by order of these elements('one','two', etc)

what I dont understand, is the function of the pair variable, and the key variable. pair i'm assuming is a placeholder necessary for the lambda function to return that value.

But is key a python keyword to be interpreted as the keys to the dictionary values, or is that an arbitrary variable used to make the lambda function work as well?

Top answer
1 of 4
5
key is just a regular argument that the list.sort() function takes. It's not special in any way. It's not a keyword. (It is a keyword-only argument, but that's not the same as being a keyword.) In other words, the list.sort() method specifically expects an argument named key that contains a callback function to be used to control the sort. You can't pass a callback function as an argument to any random old function that isn't expecting it. It also has nothing specifically to do with lambda functions; you could pass a regular function too. (Or you could pass an instance that has __call__() implemented, i.e. any callable.) pair is the name of the parameter of the anonymous function being defined. It's arbitrary; you can name your arguments whatever you want. BTW, I'd argue that that's a bad example and it should be written as import operator ... pairs.sort(key=operator.itemgetter(1))
2 of 4
2
It might help to break it down. .sort() can take a parameter "key" which has to be a function. That function has to take a (list) item and it must return something that Python knows how to sort. Its sometimes useful to shorten the declaration of function definitions that are only used in one place by omitting the function name (why name it when its clear I'm using it once right here?) In python these are called lambda functions. Their declaration is a bit different to normal functions to help with readability. Eg pairs.sort(key=lambda pair: pair[1]) is the same as: def fun(pair): return pair[1] pairs.sort(key=fun) The pair variable is just a parameter for the function. It could be called cabbage or industrial_solvent, doesn't really matter. It just makes sense to call it "pair" since your list is a list of tuple pairs. So yes, "key" is a python keyword. "pair" is not a python keyword. (Edit: technically, key is an expected keyword argument) See more here: https://docs.python.org/3/howto/sorting.html
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ howto โ€บ sorting.html
Sorting Techniques โ€” Python 3.14.3 documentation
February 23, 2026 - Objects with named attributes can be made by a regular class as shown above, or they can be instances of dataclass or a named tuple. The key function patterns shown above are very common, so Python provides convenience functions to make accessor functions easier and faster. The operator module has itemgetter(), attrgetter(), and a methodcaller() function. Using those functions, the above examples become simpler and faster: >>> from operator import itemgetter, attrgetter >>> sorted(student_tuples, key=itemgetter(2)) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] >>> sorted(student_objects, key=attrgetter('age')) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
๐ŸŒ
AskPython
askpython.com โ€บ home โ€บ 3 ways to sort a dictionary by value in python
3 Ways to Sort a Dictionary by Value in Python - AskPython
August 6, 2022 - Python lambda function creates an anonymous function i.e. a function without a name. It helps optimize the code. ... inp_dict = { 'a':3,'ab':2,'abc':1,'abcd':0 } print("Dictionary: ", inp_dict) sort_dict= dict(sorted(inp_dict.items(), key=lambda item: item[1])) print("Sorted Dictionary by value: ", sort_dict)
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ sort-dictionary-by-value-in-python
Sort Dictionary by Value in Python โ€“ How to Sort a Dict
September 13, 2022 - pass the dictionary to the sorted() method as the first value ยท use the items() method on the dictionary to retrieve its keys and values ยท write a lambda function to get the values retrieved with the item() method
๐ŸŒ
Codecademy
codecademy.com โ€บ article โ€บ how-to-sort-a-dictionary-by-key-or-value-in-python
How to Sort a Dictionary by Key or Value in Python | Codecademy
The best way to sort a dictionary in Python is by using the sorted() function along with dictionary.items() and specifying a sorting key with a lambda function.