Python – Sort List by Dictionary values
Sometimes while working with a Python dictionary, we can have problems in which we need to perform a sort of list according to the corresponding value in the dictionary. This can have applications in many domains, including data and web development. Let’s discuss certain ways in which this task can be performed.
Sort Dictionary by Value in Python using sorted()
The combination of the functions can be used to solve this problem. In this, we perform the task of sorting using sorted(). The lambda function is used to get key values.
Python3
test_list = [ 'gfg' , 'is' , 'best' ]
test_dict = { 'gfg' : 56 , 'is' : 12 , 'best' : 76 }
print ( "The original list is : " + str (test_list))
print ( "The original dictionary is : " + str (test_dict))
res = sorted (test_list, key = lambda ele: test_dict[ele])
print ( "The list after sorting : " + str (res))
|
Output :
The original list is : ['gfg', 'is', 'best']
The original dictionary is : {'best': 76, 'gfg': 56, 'is': 12}
The list after sorting : ['is', 'gfg', 'best']
Sort Dictionary by Value in Python using sorted() + key + get()
This method performs the task in a similar way as the above method. The difference is that it accesses values get().
Python3
test_list = [ 'gfg' , 'is' , 'best' ]
test_dict = { 'gfg' : 56 , 'is' : 12 , 'best' : 76 }
print ( "The original list is : " + str (test_list))
print ( "The original dictionary is : " + str (test_dict))
res = sorted (test_list, key = test_dict.get)
print ( "The list after sorting : " + str (res))
|
Output :
The original list is : ['gfg', 'is', 'best']
The original dictionary is : {'best': 76, 'gfg': 56, 'is': 12}
The list after sorting : ['is', 'gfg', 'best']
Sort List by Dictionary values using operator.itemgetter() with sorted()
This method uses the itemgetter() function from the operator module along with the sorted() function to sort the list based on the values of the dictionary.
Python3
import operator
test_list = [ 'gfg' , 'is' , 'best' ]
test_dict = { 'gfg' : 56 , 'is' : 12 , 'best' : 76 }
print ( "The original list is : " + str (test_list))
print ( "The original dictionary is : " + str (test_dict))
res = [x for x, _ in sorted (test_dict.items(),
key = operator.itemgetter( 1 ))]
print ( "The list after sorting : " + str (res))
|
Output :
The original list is : ['gfg', 'is', 'best']
The original dictionary is : {'best': 76, 'gfg': 56, 'is': 12}
The list after sorting : ['is', 'gfg', 'best']
Last Updated :
26 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...