![]() |
Python dictionaries are versatile data structures that allow you to store key-value pairs. While dictionaries maintain the order of insertion. sorting them by values can be useful in various scenarios. In this article, we’ll explore five different methods to sort a Python dictionary by its values, along with simple examples for each approach. Sort Python Dictionary by ValueBelow, are the example of Sort Python Dictionary by Value in Python.
Sort Python Dictionary by Value Using a For LoopIn this example, below code initializes a sample Dictionary with key-value pairs. It then sorts the dictionary based on its values using a for loop and creates a new dictionary called `sorted_dict`. Finally, the sorted dictionary is printed. Python3
Output
{'grape': 1, 'banana': 2, 'apple': 5, 'orange': 8} Sort Python Dictionary by Value Using
|
# Sample dictionary sample_dict = { 'apple' : 5 , 'banana' : 2 , 'orange' : 8 , 'grape' : 1 } # Sorting using sorted() method sorted_dict = {key: value for key, value in sorted (sample_dict.items(), key = lambda item: item[ 1 ])} print (sorted_dict) |
{'grape': 1, 'banana': 2, 'apple': 5, 'orange': 8}
itemgetter()
In this example, below Python code imports the itemgetter
function from the operator
module. It initializes a sample dictionary and sorts it based on values using a dictionary comprehension with the sorted()
function and itemgetter(1)
.
# Importing necessary module from operator import itemgetter # Sample dictionary sample_dict = { 'apple' : 5 , 'banana' : 2 , 'orange' : 8 , 'grape' : 1 } # Sorting using operator module and itemgetter() sorted_dict = {key: value for key, value in sorted (sample_dict.items(), key = itemgetter( 1 ))} print (sorted_dict) |
{'grape': 1, 'banana': 2, 'apple': 5, 'orange': 8}
In this example, below Python code initializes a sample dictionary and creates a new dictionary named sorted_dict
by sorting the original dictionary based on its values using the sorted()
function and a lambda function
# Sample dictionary sample_dict = { 'apple' : 5 , 'banana' : 2 , 'orange' : 8 , 'grape' : 1 } # Sorting and creating a new dictionary sorted_dict = dict ( sorted (sample_dict.items(), key = lambda item: item[ 1 ])) print (sorted_dict) |
{'grape': 1, 'banana': 2, 'apple': 5, 'orange': 8}
In conclusion, sorting a Python dictionary by its values is a common operation and can be accomplished through various methods. Whether using for loops, the `sorted()` method, the `operator` module with `itemgetter()`, lambda functions, or creating a new dictionary with sorted values, Python offers flexibility in implementing this task. Each method has its own advantages, allowing developers to choose the approach that best suits their preferences and requirements for sorting dictionaries based on values.
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |