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 C/C++ Code # Python code to demonstrate # sort a list of dictionary # where value date is in string # Initialising list of dictionary ini_list = [{'name'
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 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. [GFGTABS] Python a = [[1,
3 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
Python | Finding relative order of elements in list
Sometimes we have an unsorted list and we wish to find the actual position the elements could be when they would be sorted, i.e we wish to construct the list which could give the position to each element destined if the list was sorted. This has a good application in web development and competitive
3 min read
Convert Dictionary of Dictionaries to Python List of Dictionaries
We are given dictionary of dictionaries we need to convert it to list of dictionaries. For example, For example, we are having d = { 'A': {'color': 'red', 'shape': 'circle'}, 'B': {'color': 'blue', 'shape': 'square'}, 'C': {'color': 'green', 'shape': 'triangle'} } we need to convert it to a list of
2 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
3 min read
Filter List of Python Dictionaries by Key in Python
In Python, filtering a list of dictionaries based on a specific key is a common task when working with structured data. In this article, weâll explore different ways to filter a list of dictionaries by key from the most efficient to the least. Using List Comprehension List comprehension is a concise
3 min read
Convert Dictionary String Values to List of Dictionaries - Python
We are given a dictionary where the values are strings containing delimiter-separated values and the task is to split each string into separate values and convert them into a list of dictionaries, with each dictionary containing a key-value pair for each separated value. For example: consider this d
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