python dictionary sorting in descending order based on values

Learn python dictionary sorting in descending order based on values with practical examples, diagrams, and best practices. Covers python, dictionary development techniques with visual explanations.

Sorting Python Dictionaries by Value in Descending Order

Hero image for python dictionary sorting in descending order based on values

Learn various Python techniques to sort dictionaries based on their values in descending order, from basic methods to more advanced lambda functions.

Python dictionaries are inherently unordered collections of key-value pairs. However, there are many scenarios where you might need to sort a dictionary based on its values, especially when you want to retrieve items in a specific order, such as from highest to lowest. This article will guide you through several effective methods to achieve this, focusing on sorting in descending order.

Understanding Dictionary Sorting Limitations

It's crucial to understand that when you 'sort' a dictionary, you are not actually reordering the dictionary itself. Dictionaries in Python (from version 3.7 onwards) maintain insertion order, but they do not support sorting by value directly. Instead, sorting operations typically return a list of tuples (key, value) or a new OrderedDict (if using collections.OrderedDict) where the elements are sorted according to your criteria. The original dictionary remains unchanged.

flowchart TD
    A[Original Dictionary] --> B{Sort by Value?}
    B -- Yes --> C[Extract Key-Value Pairs]
    C --> D[Sort Pairs by Value (Descending)]
    D --> E[New Sorted List of Tuples]
    E --> F{Convert to OrderedDict?}
    F -- Yes --> G[OrderedDict]
    F -- No --> H[List of Tuples]
    B -- No --> A

Conceptual flow of sorting a Python dictionary by its values.

Method 1: Using sorted() with lambda for Descending Order

The most common and Pythonic way to sort a dictionary by its values is to use the built-in sorted() function in conjunction with a lambda function as the key argument. The sorted() function returns a new sorted list, and the lambda function specifies that the sorting should be based on the values (the second element of each key-value pair tuple). To achieve descending order, we set the reverse parameter to True.

my_dict = {'apple': 10, 'banana': 5, 'cherry': 15, 'date': 8}

# Sort by value in descending order
sorted_items_desc = sorted(my_dict.items(), key=lambda item: item[1], reverse=True)

print(sorted_items_desc)
# Output: [('cherry', 15), ('apple', 10), ('date', 8), ('banana', 5)]

# If you need a new dictionary (Python 3.7+ preserves insertion order)
sorted_dict_desc = dict(sorted_items_desc)
print(sorted_dict_desc)
# Output: {'cherry': 15, 'apple': 10, 'date': 8, 'banana': 5}

Sorting a dictionary by values in descending order using sorted() and lambda.

Method 2: Sorting by Value and then by Key (Tie-breaking)

What if two values are the same? By default, sorted() will maintain the original relative order for equal elements (stable sort). However, you might want to explicitly sort by key as a secondary criterion. You can achieve this by making the key function return a tuple, where the first element is the primary sorting criterion (value) and the second is the secondary (key). Remember to negate the value for descending order if you want to sort keys ascendingly for ties.

my_dict_with_ties = {'apple': 10, 'banana': 5, 'cherry': 15, 'date': 8, 'elderberry': 10}

# Sort by value descending, then by key ascending for ties
sorted_items_complex = sorted(
    my_dict_with_ties.items(), 
    key=lambda item: (item[1], item[0]), 
    reverse=True
)

print(sorted_items_complex)
# Output: [('cherry', 15), ('elderberry', 10), ('apple', 10), ('date', 8), ('banana', 5)]

# Notice 'elderberry' comes before 'apple' because 'e' < 'a' is FALSE, but reverse=True reverses the whole tuple comparison.
# To sort keys ascending for ties while values are descending, you need to be more explicit:

sorted_items_complex_corrected = sorted(
    my_dict_with_ties.items(), 
    key=lambda item: (-item[1], item[0]) # Negate value for descending, key for ascending
)

print(sorted_items_complex_corrected)
# Output: [('cherry', 15), ('apple', 10), ('elderberry', 10), ('date', 8), ('banana', 5)]

Sorting by value descending and then by key ascending for tie-breaking.