
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort a Dictionary in Python by Values
Python allows dictionaries to be sorted using the built-in sorted() function. In this article, we will explore different ways to sort a dictionary in Python by its values.
Sort a Dictionary Using itemgetter() method
When we use the sorted() function along with the itemgetter() method of the operator module, the dictionary will be sorted by its values. The itemgetter() function returns a callable object that fetches an item from its operand using the provided index.
Example
Following is an example that shows how to sort a dictionary by its values using itemgetter() along with the sorted() function -
from operator import itemgetter dictionary = { 'b': 2, 'a': 1, 'd': 4, 'c': 3 } # Sorting by values using itemgetter sorted_dict = dict(sorted(dictionary.items(), key=itemgetter(1))) print(sorted_dict)
Following is the output of the above program -
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Sort a Dictionary Using Lambda Function
We can also sort a dictionary by values using the sorted() function with a lambda expression as the key.
Example
Below is an example that shows how to sort a dictionary by values using a lambda function -
dictionary = { 'b': 2, 'a': 1, 'd': 4, 'c': 3 } # Sorting dictionary by values using lambda sorted_dict = dict(sorted(dictionary.items(), key=lambda item: item[1])) print(sorted_dict)
Below is the output of the above program -
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Sorting a Dictionary using OrderedDict
The OrderedDict() method from the collections module can be used to maintain the sorted order of dictionary elements based on their values.
Example
Here is an example that uses OrderedDict() to store the sorted dictionary -
from collections import OrderedDict dictionary = { 'b': 2, 'a': 1, 'd': 4, 'c': 3 } # Sorting by values and storing in OrderedDict sorted_dict = OrderedDict(sorted(dictionary.items(), key=lambda item: item[1])) print(sorted_dict)
Here is the output of the above program -
OrderedDict({'a': 1, 'b': 2, 'c': 3, 'd': 4})