Sort a Dictionary by Value in Python
There, are various ways to Sort a Dictionary by Value in Python. Here we are explaining some generally used methods for Sorting a Dictionary by Value in Python those are following.
- Using sorted() Method
- Using For Loop
- Using Bubble Sort
Initializing a Dictionary
Python3
# Example dictionary my_dict = { 'apple' : 5 , 'banana' : 2 , 'orange' : 8 , 'grape' : 3 } print (my_dict) |
Output :
{'apple': 5, 'banana': 2, 'orange': 8, 'grape': 3}
Sort a Dictionary by Value using sorted() Method
In this example code sorts a dictionary (`my_dict`) by its values in ascending order and prints the sorted dictionary (`sorted_dict`) using sorted() method.
Python3
# Sorting dictionary by values using sorted() sorted_dict = dict ( sorted (my_dict.items(), key = lambda item: item[ 1 ])) # Printing the sorted dictionary print (sorted_dict) |
Output :
{'banana': 2, 'grape': 3, 'apple': 5, 'orange': 8}
Sort a Dictionary by Value Using For Loop
In this example , below code sorts a dictionary (`my_dict`) by its values using a for loop and creates a new dictionary (`sorted_dict`) with the sorted key-value pairs.
Python3
# Sorting the dictionary by values using a for loop sorted_dict = {} for key in sorted (my_dict, key = my_dict.get): sorted_dict[key] = my_dict[key] print ( "Sorted Dictionary by Values:" , sorted_dict) |
Output :
Sorted Dictionary by Values: {'banana': 2, 'grape': 3, 'apple': 5, 'orange': 8}
Sort a Dictionary by Value Using Bubble Sort
In this example , below code implements a bubble sort algorithm to sort a dictionary (`my_dict`) by its values in ascending order and prints the sorted dictionary.
Python3
# Bubble sort implementation def bubble_sort_dict(d): items = list (d.items()) n = len (items) for i in range (n - 1 ): for j in range ( 0 , n - i - 1 ): if items[j][ 1 ] > items[j + 1 ][ 1 ]: items[j], items[j + 1 ] = items[j + 1 ], items[j] return dict (items) # Sorting dictionary by values using Bubble Sort sorted_dict_bubble = bubble_sort_dict(my_dict) # Printing the sorted dictionary print (sorted_dict_bubble) |
Output :
{'banana': 2, 'grape': 3, 'apple': 5, 'orange': 8}
Conclusion
Python offers a simple way to sort the dictionary by its values, because of the flexibility is offered by using sorted () function and the lambda functions. The steps are outlined above, along with the concepts involved should absolutely help you to adjust your dictionaries for sorting according to whichever need arises within any of your Python programs.
How to Sort a Dictionary by Value in Python
In Python, sorting a dictionary by its values is something that often comes up when we are working with the data for which there exists an ordered presentation or analysis. Python dictionaries do not have this value already ordered within it, but with a minute programming script sorting the dictionary based on its values is simple. In this article, we will see how to sort a dictionary by value in Python.