Python Program to Sort a Dictionary by Value

Updated on November 21, 2024
Sort a dictionary by value header image

Introduction

Sorting a dictionary by its values is a common task in Python programming, especially when dealing with data that needs to be organized in a specific order. Python provides several methods to effectively sort dictionaries, making it easier to manipulate and display data according to custom sorting criteria.

In this article, you will learn how to sort a dictionary by its values using different approaches in Python. These examples will cover the use of lambda functions, the sorted() function, and how to achieve both ascending and descending order sorts. Furthermore, the article will demonstrate how to handle dictionaries with complex data types as values.

Sorting Dictionary by Values in Ascending Order

Using Lambda Function

  1. Initialize a dictionary with unsorted values.

  2. Use the sorted() function along with a lambda function to sort the dictionary.

    python
    scores = {'Alice': 58, 'Bob': 75, 'Charlie': 44, 'David': 89}
    sorted_scores = sorted(scores.items(), key=lambda x: x[1])
    print(sorted_scores)
    

    In this code, scores.items() returns a list of tuples, where each tuple consists of a key-value pair. The key function in sorted()lambda x: x[1]—tells Python to sort the items by the second element of each tuple, which corresponds to the dictionary values.

Using the operator Module

  1. Import the itemgetter function from the operator module.

  2. Apply this function within the sorted() to specify the sort order.

    python
    from operator import itemgetter
    scores = {'Alice': 58, 'Bob': 75, 'Charlie': 44, 'David': 89}
    sorted_scores = sorted(scores.items(), key=itemgetter(1))
    print(sorted_scores)
    

    The itemgetter(1) function accomplishes a similar task as the lambda function in the previous example, specifying that sorting should be based on the values of dictionary items.

Sorting Dictionary by Values in Descending Order

Reverse Parameter in Sorted Function

  1. Utilize the sorted() function's reverse parameter to sort the dictionary in descending order.

  2. Combine the lambda function for value-based sorting with the reverse=True flag.

    python
    scores = {'Alice': 58, 'Bob': 75, 'Charlie': 44, 'David': 89}
    sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
    print(sorted_scores)
    

    Here, adding reverse=True to the sorted() function inverts the order of sorting, resulting in the values being sorted in descending order.

Sorting Dictionaries with Complex Data Types

Sorting Based on Custom Criteria

  1. Create a dictionary with complex data types, such as lists, as values.

  2. Define a custom sorting key function that adapts to these complex types.

    python
    data = {'item1': [10, 3], 'item2': [15, 2], 'item3': [3, 4]}
    sorted_data = sorted(data.items(), key=lambda x: (x[1][1], x[1][0]))
    print(sorted_data)
    

    In this example, the dictionary values are lists, and sorting needs to consider multiple factors—first by the second element of the list, then by the first. The lambda function lambda x: (x[1][1], x[1][0]) facilitates multi-level sorting based on list indices.

Conclusion

Sorting dictionaries by values in Python is a task that can be approached in many ways, depending on the structure of the dictionary and the desired sort order. Whether using simple lambda functions, harnessing the power of the operator module, or dealing with more complex sorting criteria, Python offers robust tools and flexible methods to order dictionaries efficiently. Explore these techniques to ensure your dictionaries are always in the right order to suit your program's needs.