Open In App

Sorting List of Dictionaries in Descending Order in Python

Last Updated : 01 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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)

Output
Bob 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.


Next Article

Similar Reads