The sorted() function takes a key= parameter

newlist = sorted(list_to_be_sorted, key=lambda d: d['name'])

Alternatively, you can use operator.itemgetter instead of defining the function yourself

from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))

For completeness, add reverse=True to sort in descending order

newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)
Answer from Mario F 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 - In this method we create a list of tuples where each tuple contains the values of the keys we want to sort by followed by the original dictionary. This list of tuples is then sorted based on the values of the keys and the sorted dictionaries ...
Discussions

How to sort a list containing dictionary items?
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. More on reddit.com
🌐 r/learnpython
4
2
September 30, 2023
Sorting a dict by its values
Hi everyone I’ve been trying to come up with the most efficient way to sort a dictionary by its values but since there aren’t any sorting methods for a dictionary, I’ve been struggling l to do so. Any ideas? Thx More on discuss.python.org
🌐 discuss.python.org
14
0
October 3, 2023
Lists, dictionaries,tuple, sort,
Hi! I have to write the following programme: Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ’ line by finding the time and then splitting the string a second time using ... More on discuss.python.org
🌐 discuss.python.org
6
0
December 16, 2021
How to sort a list of dictionaries where the keys are strings and some of them are either empty or don't exist
Dictionaries have a `get` method that allows one to specify a default value, e.g.: sorted_list = sorted(dict_list, key=lambda d: float(d.get(key, 0)), reverse=True) Alternatively, you can add missing ratings to the dictionaries with `setdefault`: sorted_list = sorted(dict_list, key=lambda d: float(d.setdefault(key, 0)), reverse=True) This latter method will modify the dictionary if the key is missing. More on reddit.com
🌐 r/learnpython
5
1
January 27, 2023
🌐
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....
🌐
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.
🌐
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 final dictionary is structured so the keys appear from Z to A (or highest to lowest if numerically labeled). But how can sorting remain predictable when dealing with edge cases like duplicate values, empty dictionaries, or frequently updated data? Python offers a stable solution—let’s explore it with OrderedDict.
🌐
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""" )
Find elsewhere
🌐
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 - The first script uses the sorted() function in combination with a lambda function to sort a list of dictionaries. The sorted() function is a built-in Python function that returns a new sorted list from the items in an iterable.
🌐
Better Stack
betterstack.com › community › questions › how-to-sort-list-of-dictionaries-in-python
How do I sort a list of dictionaries by a value of the dictionary in Python? | Better Stack Community
January 26, 2023 - In Python, you can use the sorted() function to sort a list of dictionaries by a specific value of the dictionary. The sorted() function takes two arguments: the list to be sorted, and a key function that maps each element of the list to a value ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-sort-dictionaries-list-by-keys-value-list-index
Python - Sort dictionaries list by Key's Value list index - GeeksforGeeks
April 5, 2023 - The inner key parameter is evaluated after the outer key parameter in the lambda order. Assign the sorted list of dictionaries to the variable res. Print the sorted list of dictionaries. This is modification in sorting of values, adding another parameter in case of tie of values among list. ... # Python3 code to demonstrate working of # Sort dictionaries list by Key's Value list index # Using sorted() + lambda (Additional parameter in case of tie) # initializing lists test_list = [{"Gfg": [6, 7, 9], "is": 9, "best": 10}, {"Gfg": [2, 0, 3], "is": 11, "best": 19}, {"Gfg": [4, 6, 9], "is": 16, "b
🌐
PythonHow
pythonhow.com › how › sort-a-list-of-dictionaries-by-a-value-of-the-dictionary
Here is how to sort a list of dictionaries by a value of the dictionary in Python
# Import the operator module import operator # Define a list of dictionaries my_list = [ {'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 30}, {'name': 'Bob', 'age': 20}, ] # Sort the list of dictionaries by the age value sorted_list = sorted(my_list, key=operator.itemgetter('age')) # Print the sorted list print(sorted_list)This will produce the same output as the previous example. ... Solve Python exercises and get instant AI feedback on your solutions.
🌐
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 - To sort this list by year, we can use the sorted() function, which takes a key function as an argument.
🌐
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 sorted list is iterated over, and each key-value pair is added to the sorted_dict using assignment. Another approach to sorting a dictionary by key is to use the collections.OrderedDict class from the Python standard library. This class is a dict subclass that remembers the order of its elements based on the insertion order.
🌐
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.
🌐
Grosflorida
grosflorida.weebly.com › blog › python-sort-list-of-dictionaries-by-key
Python sort list of dictionaries by key - Grosflorida
July 26, 2023 - The output will be the sorted dictionary as shown in the below example: In the method, we first create the list of the dictionary keys and sort the list of keys using the sorted() method along with...
🌐
GeeksforGeeks
geeksforgeeks.org › python › sorting-list-of-dictionaries-in-descending-order-in-python
Sorting List of Dictionaries in Descending Order in Python - GeeksforGeeks
July 23, 2025 - For example, given a list of ... 'section': 7}, {'class': '5', 'section': 3}, {'Class': 'Five', 'section': 2}]. sorted() with a lambda function is one of the most flexible and widely used methods for sorting a list of ...
🌐
Python.org
discuss.python.org › python help
Sorting a dict by its values - Python Help - Discussions on Python.org
October 3, 2023 - Hi everyone I’ve been trying to come up with the most efficient way to sort a dictionary by its values but since there aren’t any sorting methods for a dictionary, I’ve been struggling l to do so. Any ideas? Thx
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-sort-python-dictionaries-by-key-or-value
Sort Python Dictionary by Key or Value - Python - GeeksforGeeks
Loop prints key-value pairs in ascending order of their values. 4. Using NumPy: This approach uses NumPy’s argsort() for fast value-based sorting in numerical dictionaries. Python · import numpy as np d = {'alex': 10, 'ben': 9, 'clara': 15, 'diana': 2, 'eva': 32} k = list(d.keys()) v = list(d.values()) idx = np.argsort(v) res = {k[i]: v[i] for i in idx} print(res) Output ·
Published   January 13, 2026
🌐
Python.org
discuss.python.org › python help
Lists, dictionaries,tuple, sort, - Python Help - Discussions on Python.org
December 16, 2021 - Hi! I have to write the following programme: Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ’ li…
🌐
YoungWonks
youngwonks.com › blog › python-sort-dictionary-by-key-or-value
Python Sort Dictionary by Key or Value
April 10, 2023 - You can use the keys() method to return a list of all the keys in a dictionary. Sorted() is a built-in function in Python which takes an iterable object as an argument and returns a sorted list containing all of the elements of the iterable object.
🌐
Reddit
reddit.com › r/learnpython › how to sort a list of dictionaries where the keys are strings and some of them are either empty or don't exist
r/learnpython on Reddit: How to sort a list of dictionaries where the keys are strings and some of them are either empty or don't exist
January 27, 2023 -

I have a list of dictionaries coming from a rest API,

myList = [
{ 'id' : 1, 'rating' : "14" },
{ 'id': 2},
{ 'id': 3, 'rating': "" },     
{ 'id': 4, 'rating': "20.1"}
]

I'm trying to sort it by key="rating"

sorted_list = sorted(dict_list, key=lambda d: float(d[key]), reverse=True)

I'm getting this error

TypeError: string indices must be integers

This is because the rating is either empty or sometimes nonexistent. In that case how to make the rating=0 so that the sorting works?

Top answer
1 of 4
2
Dictionaries have a `get` method that allows one to specify a default value, e.g.: sorted_list = sorted(dict_list, key=lambda d: float(d.get(key, 0)), reverse=True) Alternatively, you can add missing ratings to the dictionaries with `setdefault`: sorted_list = sorted(dict_list, key=lambda d: float(d.setdefault(key, 0)), reverse=True) This latter method will modify the dictionary if the key is missing.
2 of 4
1
Just define a short helper function that wraps the dictionary.get in a try/except, like this: def sort_key(item): try: return float(item['rating']) except (ValueError,KeyError): return 0 data = [ { 'id' : 1, 'rating' : "14" }, { 'id': 2}, { 'id': 3, 'rating': "" }, { 'id': 4, 'rating': "20.1"} ] print(sorted(data, key = sort_key)) edit: Forgot that sorted does not sort in place... fixed edit2: Does a bunch of tildes turn your response to a code block? edit3: Actually dataclasses might be a good one here: from dataclasses import dataclass from operator import attrgetter @dataclass class Movie(): id: int rating: float = 0 @property def key(self): if self.rating: return float(self.rating) return 0 myList = [ { 'id' : 1, 'rating' : "14" }, { 'id': 2}, { 'id': 3, 'rating': "" }, { 'id': 4, 'rating': "20.1"} ] movies = [Movie(*m.values()) for m in myList] print(movies) key = attrgetter('key') print(sorted(movies, key = key)) last edit: Fixing them on the way in is definitely the way to go: from dataclasses import dataclass from operator import attrgetter @dataclass class Movie(): id: int rating: float = 0 def __post_init__(self): if self.rating: self.rating = float(self.rating) else: self.rating = 0 myList = [ { 'id' : 1, 'rating' : "14" }, { 'id': 2}, { 'id': 3, 'rating': "" }, { 'id': 4, 'rating': "20.1"} ] movies = [Movie(*m.values()) for m in myList] print(movies) key = attrgetter('rating') print(sorted(movies, key = key))