Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Sort List of Lists Ascending and then Descending in Python
Next article icon

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.

Table of Content

  • Using itemgetter
  • Using attrgetter
  • Using collections.Counter

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
Sort List of Lists Ascending and then Descending in Python

A

am8254s3a
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python dictionary-programs
Practice Tags :
  • python

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
  • Combine keys in a list of dictionaries in Python
    Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform a merge of dictionaries in list with similar keys. This kind of problem can come in data optimization domains. Let's discuss a way in which this task can be performed. Input : test_list = [{'a': 6},
    2 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. [GFGTABS] Python a = [[1,
    3 min read
  • Python | Segregating key's value in list of dictionaries
    While working with dictionaries, we may encounter problems in which we need to segregate all the similar keys' values together. This kind of problem can occur in web development domain while working with databases. Let's discuss certain ways in which this problem can be solved. Method #1: Using gene
    6 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
  • 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences