Sorting List of Dictionaries in Descending Order in Python
Last Updated :
01 Feb, 2025
The task of sorting a list of dictionaries in descending order involves organizing the dictionaries based on a specific key in reverse order. For example, given a list of dictionaries like a = [{'class': '5', 'section': 3}, {'Class': 'Five', 'section': 7}, {'Class': 'Five', 'section': 2}], the goal is to sort the dictionaries by the 'section' key in descending order, resulting in a = [{'Class': 'Five', 'section': 7}, {'class': '5', 'section': 3}, {'Class': 'Five', 'section': 2}].
Using sorted()
sorted() with a lambda function is one of the most flexible and widely used methods for sorting a list of dictionaries. It allows us to specify a custom sorting key dynamically, making it highly adaptable for different use cases. The lambda function extracts the required key from each dictionary for sorting.
Python
a = [{'class': '5', 'section': 3}, {'Class': 'Five', 'section': 7}, {'Class': 'Five', 'section': 2}]
res = sorted(a, key=lambda x: x['section'], reverse=True)
print(res)
Output[{'Class': 'Five', 'section': 7}, {'class': '5', 'section': 3}, {'Class': 'Five', 'section': 2}]
Explanation: sorted() uses a lambda function (lambda x: x['section']) to extract the sorting key and reverse=True ensures the order is from highest to lowest.
Using itemgetter
itemgetter() from operator module is optimized for retrieving dictionary keys, making sorting faster than using a lambda function in some cases. It reduces the overhead of function calls, making it slightly more efficient for simple key-based sorting. This method is ideal when sorting by a single key and provides better readability.
Python
from operator import itemgetter
a = [{'class': '5', 'section': 3}, {'Class': 'Five', 'section': 7}, {'Class': 'Five', 'section': 2}]
res = sorted(a, key=itemgetter('section'), reverse=True)
print(res)
Output[{'Class': 'Five', 'section': 7}, {'class': '5', 'section': 3}, {'Class': 'Five', 'section': 2}]
Explanation: sorted() uses itemgetter('section') from the operator module, which retrieves the value of 'section' for sorting. The reverse=True argument ensures sorting is done in descending order.
Using attrgetter
If sorting a list of objects instead of dictionaries, attrgetter() from the operator module provides a more efficient way to access object attributes directly. It works similarly to itemgetter() but is used for objects rather than dictionaries. This method avoids function call overhead, making it more efficient than a lambda function for sorting class instances.
Python
from operator import attrgetter
from collections import namedtuple
# Define a namedtuple to represent the student
Student = namedtuple('Student', ['name', 'section'])
a = [Student('Alice', 3), Student('Bob', 7), Student('Charlie', 2)]
res = sorted(a, key=attrgetter('section'), reverse=True)
for student in res:
print(student.name, student.section)
OutputBob 7
Alice 3
Charlie 2
Explanation: This code defines a Student namedtuple with 'name' and 'section' attributes and creates a list of student objects. The sorted() function, using attrgetter('section'), sorts them in descending order based on the 'section' attribute. Finally, a loop prints each student's name and section.
Using collections.Counter
Counter class from collections is primarily used for counting occurrences of elements, but it can also assist in sorting dictionaries based on frequency. However, this method is not optimized for direct sorting and introduces additional overhead in creating and managing frequency counts.
Python
from collections import Counter
a = [{'class': '5', 'section': 3}, {'Class': 'Five', 'section': 7}, {'Class': 'Five', 'section': 2}]
counter = Counter([item['section'] for item in a]) # Count occurrences of each 'section' value
res = sorted(a, key=lambda x: counter[x['section']], reverse=True)
print(res)
Output[{'class': '5', 'section': 3}, {'Class': 'Five', 'section': 7}, {'Class': 'Five', 'section': 2}]
Explanation: sorted() sorts the list of dictionaries based on the frequency of the 'section' values, using the counter to retrieve the count for each 'section'. The reverse=True ensures the sorting is in descending order, placing more frequent values first.
Similar Reads
Python | Sort given list of dictionaries by date Given a list of dictionary, the task is to sort the dictionary by date. Let's see a few methods to solve the task. Method #1: Using naive approach Python3 # Python code to demonstrate # sort a list of dictionary # where value date is in string # Initialising list of dictionary ini_list = [{'name':'a
2 min read
Python - Sort list of Single Item dictionaries according to custom ordering Given single item dictionaries list and keys ordering list, perform sort of dictionary according to custom keys. Input : test_list1 = [{'is' : 4}, {"Gfg" : 10}, {"Best" : 1}], test_list2 = ["Gfg", "is", "Best"] Output : [{'Gfg': 10}, {'is': 4}, {'Best': 1}] Explanation : By list ordering, dictionari
4 min read
Sort Nested Dictionary by Value Python Descending Sorting a nested dictionary in Python based on its values is a common task, and it becomes even more versatile when you need to sort in descending order. In this article, we'll explore some different methods to achieve this using various Python functionalities. Let's dive into more ways to efficient
3 min read
Sort List of Lists Ascending and then Descending in Python Sorting a list of lists in Python can be done in many ways, we will explore the methods to achieve the same in this article.Using sorted() with a keysorted() function is a flexible and efficient way to sort lists. It creates a new list while leaving the original unchanged.Pythona = [[1, 2, 3], [3, 2
3 min read
Get Items in Sorted Order from Given Dictionary - Python We are given a dictionary where the values are strings and our task is to retrieve the items in sorted order based on the values. For example, if we have a dictionary like this: {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'} then the output will be ['akshat', 'bhuvan', 'chandan']Using sorted() with
2 min read
Python - Convert Dictionaries List to Order Key Nested dictionaries Given list of dictionaries, our task is to convert a list of dictionaries into a dictionary where each key corresponds to the index of the dictionary in the list and the value is the dictionary itself. For example: consider this list of dictionaries: li = [{"Gfg": 3, 4: 9}, {"is": 8, "Good": 2}] the
3 min read
Sort Dictionary by Value Python Descending Sometimes, we need to sort the dictionary by value in reverse order or descending order. We can perform this task easily by using Python. In this article, we will learn to Sort the Dictionary by Value in Descending Order using Python Programming. Below is an example to understand the problem stateme
4 min read
Sort a List of Python Dictionaries by a Value Sorting a list of dictionaries by a specific value is a common task in Python programming. Whether you're dealing with data manipulation, analysis, or simply organizing information, having the ability to sort dictionaries based on a particular key is essential. In this article, we will explore diffe
3 min read
Sort List of Dictionaries by Multiple Keys - Python We are given a list of dictionaries where each dictionary contains various keys and our task is to sort the list by multiple keys. Sorting can be done using different methods such as using the sorted() function, a list of tuples, itemgetter() from the operator module. For example, if we have the fol
3 min read
Sort a List of Dictionaries by a Value of the Dictionary - Python We are given a list of dictionaries where each dictionary contains multiple key-value pairs and our task is to sort this list based on the value of a specific key. For example, Given the list: students = [{'name': 'David', 'score': 85}, {'name': 'Sophia', 'score': 92}, {'name': 'Ethan', 'score': 78}
2 min read