How to Sort a Dictionary by Value in Python

Are you exploring different methods for sorting dictionaries by value in Python? Sorting dictionaries is a common operation in Python that can assist in organizing and analyzing the data in an efficient manner.

In today’s guide, we will demonstrate several approaches for sorting dictionaries by value such as the sorted() function, itemgetter() method, lambda function, bubble sort, items() method, for loop, and custom sorting algorithm.

By having knowledge about these techniques, you can gain valuable insights related to sorting dictionaries by value. Resultantly, you will be able to manipulate the data in a better way and make efficient decisions regarding your Python projects.

What are Python Dictionaries

Python dictionaries are the data structures that are utilized for storing the key-value pairs. These structures offer an efficient way of storing, fetching, and manipulating data.

More specifically, the dictionaries are mutable and unordered, enabling you to modify the values and access them easily according to the associated keys.

Understanding Dictionary Values in Python

Dictionary values are the data elements that are associated with each key. These values can belong to any type, like numbers, strings, lists, or other dictionaries. Moreover, they serve as a reference to more complex data structures or hold meaningful information.

How to Create a Python Dictionary

To create a dictionary, specify its name and define the key-value pair inside the {} parentheses as follows.

authors = {'Sharqa': 6, 'Ravi': 2, 'tulsi': 10, 'Kenny': 1}

Here, the “authors” dictionary comprises the “names” as keys and the “values” of the corresponding author scores.

Benefits of Sorting Dictionaries by Value

Have a look at the given benefits of sorting dictionaries by value in Python.

  • Facilitates the decision-making processes and data analysis.
  • Organizes data based on the value characteristics, such as numeric or alphabetical order.
  • Display information in a readable and structured manner.
  • Supports efficient retrieval of values according to the relative order.
  • Enables identification of the patterns, distribution, and trends within the data.
  • Improves data visualization capabilities.

How to Sort a Dictionary by Value in Python

In order to sort a dictionary by value, you can check out the following approaches.

  • The sorted() Function
  • The itemgetter() Function of the Operator Module
  • The lambda Function
  • Custom Sorting Algorithm
  • for loop
  • The items() Method
  • Bubble Sort Algorithm

Using sorted() Function

In Python, “sorted()” is a built-in function that can be utilized for sorting an iterable in ascending order. This function outputs a new sorted list. You can also use it for sorting the dictionaries based on their values.

For instance, in the given program, we have invoked the “sorted()” function for sorting the “authors” dictionary based on its values. To do so, the “key” parameter is specified as “authors.get“, which means that the sorting should be done on the values.

The resultant sorted dictionary is stored in the “sorted_dict” variable. Lastly, a “for” loop is used for printing the dictionary on the console.

# Dictionary to be sorted
authors = {'Sharqa': 6, 'Ravi': 2, 'Tulsi': 10, 'Kenny': 1}

# Sorting the dictionary by values
sorted_dict = sorted(authors, key=authors.get)

# Printing the sorted dictionary
for key in sorted_dict:
    print(key, authors[key])

It can be observed that the “authors” dictionary has been successfully sorted based on the values.

Python Dictionary Using sorted() Function
Python Dictionary Using sorted() Function

Using itemgetter() Function of the Operator Module

The Python “operator” module offers a set of functions that can be utilized as the functional equivalent of the common operators. For instance, its “itemgetter()” function is used for fetching the items from the given object based on the defined keys or indices.

This method also enables you to sort dictionaries based on the keys or values.

In this example, we have used the “itemgetter()” function as the key argument of the “sorted()” function. This function will sort the “authors” dictionary by its values.

More specifically, the “operator.itemgetter(1)” signifies that the sorting must be done based on the values (index 1). Likewise, the sorted dictionary will be stored in the “sorted_dict” variable and printed on the terminal using a for loop.

import operator

# Dictionary to be sorted
authors = {'Sharqa': 6, 'Ravi': 2, 'Tulsi': 10, 'Kenny': 1}

# Sorting the dictionary by values using itemgetter()
sorted_dict = dict(sorted(authors.items(), key=operator.itemgetter(1)))

# Printing the sorted dictionary
for key, value in sorted_dict.items():
    print(key, value)
Using itemgetter() Function of the Operator Module
Using itemgetter() Function of the Operator Module

Using lambda Function

Anonymous or lambda functions are inline, small functions that do not need a separate name. These functions are primarily utilized for simple operations. However, you can combine a lambda function with sorted() for sorting the dictionaries based on the defined condition.

Here, in this scenario, the lambda function is called the key argument in the “sorted()” function for sorting the “authors” dictionary based on its values. The lambda function “lambda x: x[1]” defines that the sorting will be done based on the second element which is the value of each pair.

# Dictionary to be sorted
authors = {'Sharqa': 6, 'Ravi': 2, 'Tulsi': 10, 'Kenny': 1}

# Sorting the dictionary by values using lambda
sorted_dict = dict(sorted(authors.items(), key=lambda x: x[1]))

# Printing the sorted dictionary
for key, value in sorted_dict.items():
    print(key, value)
Using lambda Function
Using lambda Function

Using a Custom Sorting Algorithm

In Python, custom sorting algorithms are implemented for sorting dictionaries according to the defined requirements. The main advantage of using this technique is that you will have full control over the sorting criteria and logic that is going to be applied to the dictionary.

Now, let’s implement a custom sorting function named “custom_sort()“. This function will take the “authors” dictionary as input. Then, it sorts it according to the added lambda function. Lastly, the sorted dictionary based on the values will be stored in the “sorted_dict” variable.

# Dictionary to be sorted
authors = {'Sharqa': 6, 'Ravi': 2, 'Tulsi': 10, 'Kenny': 1}

# Custom sorting function
def custom_sort(dictionary):
    return {k: v for k, v in sorted(dictionary.items(), key=lambda item: item[1])}

# Sorting the dictionary using the custom sort function
sorted_dict = custom_sort(authors)

# Printing the sorted dictionary
for key, value in sorted_dict.items():
    print(key, value)
Using a Custom Sorting Algorithm
Using a Custom Sorting Algorithm

Using a for loop Function

Another approach for sorting dictionaries based on the values is to use the “for” loop. This method comprises the steps of iterating over the dictionary key-value pairs, fetching them into a list, and then sorting the list based on the given condition.

More specifically, for loop permits you to customize and manually control the sorting process.

For instance, we have now used the for loop for iterating over the keys of the “authors” dictionary in sorted order. Then, the sorted keys are used for creating a new dictionary named “sorted_dict” by fetching the corresponding values from the “authors” dictionary.

Lastly, another for loop is added for displaying the sorted dictionary on the terminal.

# Dictionary to be sorted
authors = {'Sharqa': 6, 'Ravi': 2, 'Tulsi': 10, 'Kenny': 1}

# Sorting the dictionary using a for loop
sorted_dict = {}
for key in sorted(authors, key=authors.get):
    sorted_dict[key] = authors[key]

# Printing the sorted dictionary
for key, value in sorted_dict.items():
    print(key, value)
Using a for loop Function
Using a for loop Function

Using items() Method

Python’s “items()” method outputs a view object that comprises the key-value pairs as tuples. By utilizing this method in combination with the sorted() function, you can easily sort a dictionary according to the given criteria.

Here, the “items()” method is called for obtaining a view object which comprises key-value pairs from the “authors” dictionary. As the next step, this view object is passed as an argument to the sorted() function along with the lambda function.

This combination will help to sort the dictionary according to the added value.

# Dictionary to be sorted
authors = {'Sharqa': 6, 'Ravi': 2, 'Tulsi': 10, 'Kenny': 1}

# Sorting the dictionary using the items() method
sorted_dict = dict(sorted(authors.items(), key=lambda item: item[1]))

# Printing the sorted dictionary
for key, value in sorted_dict.items():
    print(key, value)
Using items() Method
Using items() Method

Using the Bubble Sort Algorithm

Bubble sort is another simple sorting algorithm that iterates through the list that needs to be sorted. It compares the adjacent elements and swaps them if they are in the wrong order. It is not the most efficient algorithm but is still used for sorting dictionaries based on their values.

In the given program, a bubble sort algorithm is applied for sorting the “authors” dictionary. To do so, a copy of the original dictionary has been stored in the “sorted_dict“.

Then, the algorithm iterates over the “authors” dictionary with the nested for loop. Within these loops, adjacent values are compared and swapped if they are in the wrong order.

After sorting, the sorted dictionary is placed in the “sorted_dict“. Lastly, a for loop is added for displaying the sorted dictionary on the terminal.

# Dictionary to be sorted
authors = {'Sharqa': 6, 'Ravi': 2, 'Tulsi': 10, 'Kenny': 1}

# Sorting the dictionary using bubble sort
sorted_dict = dict(authors)
keys = list(sorted_dict.keys())
n = len(keys)
for i in range(n - 1):
    for j in range(n - i - 1):
        if sorted_dict[keys[j]] > sorted_dict[keys[j + 1]]:
            keys[j], keys[j + 1] = keys[j + 1], keys[j]

# Creating a new dictionary with sorted keys
new_dict = {key: sorted_dict[key] for key in keys}

# Printing the sorted dictionary
for key, value in new_dict.items():
    print(key, value)
Using the Bubble Sort Algorithm
Using the Bubble Sort Algorithm

Best Practices for Sorting Python Dictionaries by Value

Have a look at the enlisted best practices for sorting dictionaries based on the values.

  • Utilize “sorted()” with “key=dict.get()” for sorting dictionaries by values.
  • Customize sorting with the help of the lambda function as the key parameter.
  • Use the “itemgetter()” method for value-based sorting.
  • Consider time complexity while handling large dictionaries.
  • Take memory requirements into account.
  • Keep in mind the requirement of preserving the original order.
  • Test and verify the sorting result for accuracy.
Conclusion

Sorting dictionaries by values in Python provides multiple methods having their own advantages and limitations. For instance, the “sorted()” function is simple but it does not preserve the order. On the other hand, the “itemgetter()” method offers customization, however, it imports the operator module.

Lambda functions also support flexibility but may be less familiar. Therefore, you have to select the best sorting approach for your program.

You can also check out our dedicated Python Tutorial series!

If you read this far, tweet to the author to show them you care. Tweet a thanks
As a professional content writer with 3 years of experience, I specialize in creating high-quality, SEO-optimized content that engages, attracts, and retains the audience.

Each tutorial at GeeksVeda is created by a team of experienced writers so that it meets our high-quality standards.

Join the GeeksVeda Weekly Newsletter (More Than 5,467 Programmers Have Subscribed)
Was this article helpful? Please add a comment to show your appreciation and support.

Got Something to Say? Join the Discussion...