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 1: 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 results respectively.
Python3
# 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) |
The original dictionary is : {'is': [1, 2], 'best': [1, 3, 4], 'gfg': [3]} Sorted keys by value list : gfg is best
Method 2: Using collections.OrderedDict()
collections.OrderedDict() can be used to perform the same task.
Python3
# Python3 code to demonstrate working of # Sort dictionary by value list length # using collections.OrderedDict() # Importing OrderedDict from collections from collections import OrderedDict # 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 collections.OrderedDict() # Sort dictionary by value list length res = OrderedDict( sorted (test_dict.items(), key = lambda x : len (x[ 1 ]))).keys() # printing result print ( "Sorted keys by value list : " + str (res)) #This code is contributed by Edula Vinay Kumar Reddy |
The original dictionary is : {'is': [1, 2], 'gfg': [3], 'best': [1, 3, 4]} Sorted keys by value list : odict_keys(['gfg', 'is', 'best'])
Time Complexity: O(N log N)
Auxiliary Space: O(N)
Method 3: Using list comprehension + sorted() + len()
- Initialize the dictionary with key-value pairs as given in the problem statement.
- Create a list of tuples containing the key-value pairs of the dictionary using list comprehension.
- Sort the list of tuples based on the length of the value list using the sorted() method and the len() function.
- Create a new list of sorted keys by extracting the keys from the sorted list of tuples using a list comprehension.
- Print the original dictionary and the sorted list of keys.
Python3
# 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 list comprehension + sorted() + len() # Sort dictionary by value list length res = [k for k, v in sorted (test_dict.items(), key = lambda item: len (item[ 1 ]))] # printing result print ( "Sorted keys by value list : " + str (res)) |
The original dictionary is : {'is': [1, 2], 'gfg': [3], 'best': [1, 3, 4]} Sorted keys by value list : ['gfg', 'is', 'best']
Time Complexity: O(n*logn) where n is the number of items in the dictionary.
Auxiliary Space: O(n)
Method 4: Use the heapq module
Python3
import heapq # Initialize dictionary test_dict = { 'is' : [ 1 , 2 ], 'gfg' : [ 3 ], 'best' : [ 1 , 3 , 4 ]} # Create empty heap heap = [] # Loop through items and append to heap for k, v in test_dict.items(): heapq.heappush(heap, ( len (v), k)) # Extract smallest elements from heap and reverse the order res = [heapq.heappop(heap)[ 1 ] for _ in range ( len (heap))] # Print result print ( "Sorted keys by value list : " + str (res)) |
Sorted keys by value list : ['gfg', 'is', 'best']
Time complexity: O(n log n) (where n is the number of items in the dictionary)
Auxiliary space: O(n) (to store the heap)
Method 5: Using built-in zip() function and a list comprehension:
Python3
# Python3 code to demonstrate working of # Sort dictionary by value list length # using zip() and list comprehension # 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 zip() and list comprehension # Sort dictionary by value list length res = [k for _, k in sorted ( zip ( map ( len , test_dict.values()), test_dict.keys()))] # Printing result print ( "Sorted keys by value list: " + ' ' .join(res)) |
The original dictionary is: {'is': [1, 2], 'gfg': [3], 'best': [1, 3, 4]} Sorted keys by value list: gfg is best
Time complexity: O(n log n) (where n is the number of items in the dictionary)
Auxiliary space: O(n) (to store the heap)
Contact Us