How to Sort Python Dictionaries by Key or Value

NISHANT TIWARI 07 Mar, 2024 • 5 min read

Introduction

Python dictionaries are an essential data structure that allows you to store and retrieve key-value pairs efficiently. However, there may be instances where you need to sort the dictionary based on either the keys or the values. In this article, we will explore various techniques to sort Python dictionaries by key or value, along with their performance comparison and pros and cons.

How to Sort Python Dictionaries by Key or Value

What is a Python Dictionary?

A Python dictionary is an unordered collection of key-value pairs. It is implemented as a hash table, which provides fast access to values based on their keys. Dictionaries are mutable and can store values of different data types. To access a value in a dictionary, you need to provide its corresponding key.

Python dictionaries

Importance of Sorting Python Dictionaries

Sorting dictionaries can be useful in scenarios where you want to retrieve the data in a specific order. For example, if you have a dictionary containing student names as keys and their corresponding scores as values, sorting the dictionary by scores can help you identify the top-performing students easily. Sorting dictionaries also allows you to perform operations like finding the minimum or maximum value, filtering data based on certain criteria, or displaying data in a more organized manner.

Sorting Python Dictionaries by Key

Sorting Python Dictionaries by Key

There are several techniques to sort Python dictionaries by key. Let’s explore them one by one.

Using the sorted() Function

The sorted() function in Python returns a new list containing all items from the original dictionary, sorted in ascending order by key. Here’s an example:

Code:

student_scores = {'Aayush': 85, 'Himanshu': 78, 'Nishant': 95, 'DeepSandhya': 92}
sorted_scores = sorted(student_scores.items())
print(sorted_scores)

Output:

[('Aayush', 85), ('DeepSandhya', 92), ('Himanshu', 78), ('Nishant', 95)]

Using the keys() Method

The keys() method returns a view object that contains the keys of the dictionary. By converting this view object into a list and sorting it, we can achieve the desired result. Here’s an example:

Code:

student_scores = {'Aayush': 85, 'Himanshu': 78, 'Nishant': 95, 'DeepSandhya': 92}
sorted_scores = sorted(student_scores.keys())
print(sorted_scores)

Output:

['Aayush', 'DeepSandhya', 'Himanshu', 'Nishant']

Using the operator.itemgetter() Function

The operator.itemgetter() function allows us to specify the key based on which we want to sort the dictionary. Here’s an example:

Code:

import operator
student_scores = {'Aayush': 85, 'Himanshu': 78, 'Nishant': 95, 'DeepSandhya': 92}
sorted_scores = sorted(student_scores.items(), key=operator.itemgetter(0))
print(sorted_scores)

Output:

[('Aayush', 85), ('DeepSandhya', 92), ('Himanshu', 78), ('Nishant', 95)]

Using a Lambda Function

Lambda functions are anonymous functions that can be used to define simple functions in a single line. We can use a lambda function to specify the key based on which we want to sort the dictionary. Here’s an example:

Code:

student_scores = {'Aayush': 85, 'Himanshu': 78, 'Nishant': 95, 'DeepSandhya': 92}
sorted_scores = sorted(student_scores.items(), key=lambda x: x[0])
print(sorted_scores)

Output:

[('Aayush', 85), ('DeepSandhya', 92), ('Himanshu', 78), ('Nishant', 95)]

Sorting Python Dictionaries by Value

Sorting Python Dictionaries by Value

Similar to sorting by key, we can also sort Python dictionaries by value. Let’s explore the techniques for sorting dictionaries by value.

Using the sorted() Function with a Custom Key

We can use the sorted() function with a custom key to sort the dictionary by value. Here’s an example:

Code:

student_scores = {'Aayush': 85, 'Himanshu': 78, 'Nishant': 95, 'DeepSandhya': 92}
sorted_scores = sorted(student_scores.items(), key=lambda x: x[1])
print(sorted_scores)

Output:

[('Himanshu', 78), ('Aayush', 85), ('DeepSandhya', 92), ('Nishant', 95)]

Using the operator.itemgetter() Function

Similar to sorting by key, we can use the operator.itemgetter() function to specify the key based on which we want to sort the dictionary. Here’s an example:

Code:

import operator
student_scores = {'Aayush': 85, 'Himanshu': 78, 'Nishant': 95, 'DeepSandhya': 92}
sorted_scores = sorted(student_scores.items(), key=operator.itemgetter(1))
print(sorted_scores)

Output:

[('Himanshu', 78), ('Aayush', 85), ('DeepSandhya', 92), ('Nishant', 95)]

Using a Lambda Function

We can also use a lambda function to specify the key based on which we want to sort the dictionary. Here’s an example:

Code:

student_scores = {'Aayush': 85, 'Himanshu': 78, 'Nishant': 95, 'DeepSandhya': 92}
sorted_scores = sorted(student_scores.items(), key=lambda x: x[1])
print(sorted_scores)

Output:

[('Himanshu', 78), ('Aayush', 85), ('DeepSandhya', 92), ('Nishant', 95)]

Comparing Different Sorting Techniques

Now that we have explored various techniques to sort Python dictionaries by key or value, let’s compare their performance and discuss their pros and cons.

Performance Comparison

The performance of different sorting techniques can vary based on the size of the dictionary and the specific requirements of the sorting operation. However, in general, the sorted() function with a custom key or a lambda function tends to be more efficient than using the keys() method or the operator.itemgetter() function. This is because the sorted() function internally uses the Timsort algorithm, which has a time complexity of O(n log n).

Pros and Cons of Each Technique

  • Using the sorted() function: This technique is simple and versatile, allowing you to sort dictionaries by key or value with ease. However, it may not be the most efficient option for large dictionaries.
  • Using the keys() method: This technique is straightforward and can be useful if you only need to sort the keys. However, it requires converting the view object into a list, which can consume additional memory.
  • Using the operator.itemgetter() function: This technique provides a concise way to specify the key for sorting. However, it requires importing the operator module and may not be as intuitive for beginners.
  • Using a lambda function: This technique allows you to define the sorting key inline, making it convenient for simple sorting operations. However, it may not be suitable for complex sorting requirements.

Additional Sorting Options

Apart from sorting dictionaries by key or value, there are a few additional sorting options worth exploring.

Sorting in Reverse Order

To sort a dictionary in reverse order, you can pass the `reverse=True` argument to the sorted() function. Here’s an example:

Code:

student_scores = {'Aayush': 85, 'Himanshu': 78, 'Nishant': 95, 'DeepSandhya': 92}
sorted_scores = sorted(student_scores.items(), key=lambda x: x[1], reverse=True)
print(sorted_scores)

Output:

[('Nishant', 95), ('DeepSandhya', 92), ('Aayush', 85), ('Himanshu', 78)]

Sorting by Multiple Keys

If you have a dictionary with multiple keys, you can sort it based on multiple criteria. Here’s an example:

Code:

student_scores = {'Aayush': {'Math': 85, 'Science': 90}, ‘Deepsandhya’: {'Math': 92, 'Science': 88}, 'Himanshu': {'Math': 78, 'Science': 95}}
sorted_scores = sorted(student_scores.items(), key=lambda x: (x[1]['Math'], x[1]['Science']))
print(sorted_scores)

Output:

[('Himanshu', {'Math': 78, 'Science': 95}), ('Aayush', {'Math': 85, 'Science': 90}), ('Deepsandhya', {'Math': 92, 'Science': 88})]

Conclusion

Sorting Python dictionaries by key or value is a common requirement in many applications. In this article, we explored various techniques to achieve this, including using the sorted() function, the keys() method, and the operator.itemgetter() function, and lambda functions. We also discussed their performance comparison and pros and cons. Additionally, we explored sorting dictionaries in reverse order and by multiple keys. By understanding these techniques, you can effectively sort dictionaries in Python based on your specific requirements.

NISHANT TIWARI 07 Mar 2024

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers