Python | Sort dictionary by value list length

While working with Python, one might come to a problem in which one needs to perform a sort on dictionary list value length. This can be typically in case of scoring or any type of count algorithm. Let’s discuss a method by which this task can be performed.

Method : Using sorted() + join() + lambda
The combination of above functions can be used to perform this particular task. In this, we just use the lambda function to perform this particular task, sorted and join function perform the required sorting and encapsulation of result respectively.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Sort dictionary by value list length
# using sorted() + join() + lambda
  
# Initialize dictionary
test_dict = {'is' : [1, 2], 'gfg' : [3], 'best' : [1, 3, 4]}
  
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# using sorted() + join() + lambda
# Sort dictionary by value list length
res = ' '.join(sorted(test_dict, key = lambda key: len(test_dict[key])))
  
# printing result 
print("Sorted keys by value list : " + res)

chevron_right


Output :

The original dictionary is : {'is': [1, 2], 'best': [1, 3, 4], 'gfg': [3]}
Sorted keys by value list : gfg is best


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.