Python | Sort dictionary by value list length
Last Updated :
26 Apr, 2023
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)
Output : 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
OutputThe 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))
OutputThe 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))
OutputSorted 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))
OutputThe 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)
Similar Reads
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
3 min read
Python - Sort Dictionary key and values List Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the sorting of it, wrt keys, but also can have a variation in which we need to perform a sort on its values list as well. Let's discuss certain way in which this task can be performed. Input : test_d
6 min read
Sort Python Dictionary by Value 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, a
3 min read
Sort a Nested Dictionary by Value in Python Sorting a nested dictionary in Python involves understanding its structure, defining sorting criteria, and utilizing the `sorted()` function or `.sort()` method with a custom sorting function, often a lambda. This process is essential for organizing complex, hierarchical data efficiently. Mastery of
3 min read
Python - Sort Dictionary List by Key's ith Index value Given List of dictionaries, sort dictionaries on basis of Key's ith index value Input : [{"Gfg" : "Best", "for" : "Geeks"}, {"Gfg" : "Good", "for" : "Me"}, {"Gfg" : "Better", "for" : "All"}], K = "Gfg", i = 1 Output : [{'Gfg': 'Best', 'for': 'Geeks'}, {'Gfg': 'Better', 'for': 'All'}, {'Gfg': 'Good',
7 min read