Open In App

Python – How to Sort a Dictionary by Kth Index Value

Last Updated : 27 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

While working with Python, one might come to a problem in which one needs to perform a sort on a dictionary based on Kth index of value list. This can be typically in the case of scoring or web development. Let’s discuss a method by which this task can be performed.

Input : test_dict = {'gfg' : [5, 6, 7], 'is' : [1, 4, 7], 'best' : [8, 3, 1]}, K = 2 
Output : [('best', [8, 3, 1]), ('gfg', [5, 6, 7]), ('is', [1, 4, 7])]
Input : test_dict = {'gfg' : [5, 6, 7], 'is' : [1, 4, 7], 'best' : [8, 3, 1]}, K = 0 
Output : [('is', [1, 4, 7]), ('gfg', [5, 6, 7]), ('best', [8, 3, 1])]

Sort a Dictionary by Kth Index Value Using sorted() + lambda 

The combination of the above functions can be used to solve this problem. In this, we perform sort using sorted() and lambda function is used to drive Kth index logic. 

Python3




# Python3 code to demonstrate working of
# Sort Dictionary by Kth Index Value
# Using sorted() + lambda
 
# initializing dictionary
test_dict = {'gfg': [5, 6, 7],
             'is': [1, 4, 7],
             'best': [8, 3, 1]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing K
K = 1
 
# Sort Dictionary by Kth Index Value
# Using sorted() + lambda
res = sorted(test_dict.items(), key=lambda key: key[1][K])
 
# printing result
print("The sorted dictionary : " + str(res))


Output

The original dictionary is : {'gfg': [5, 6, 7], 'is': [1, 4, 7], 'best': [8, 3, 1]}
The sorted dictionary : [('best', [8, 3, 1]), ('is', [1, 4, 7]), ('gfg', [5, 6, 7])]

Time Complexity: O(nlogn), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list

Sort a Dictionary by Kth Index Value Using itemgetter() from operator module

  • First, import the itemgetter function from the operator module using the line from operator import itemgetter.
  • Next, create a dictionary named test_dict with key-value pairs. Each key is a string and each value is a list of integers.
  • Print the original dictionary using print(“The original dictionary is : ” + str(test_dict)).
  • Initialize a variable K to a specific integer value, e.g., K = 1.
  • Sort the dictionary based on the Kth index value in each value list using the sorted() function with the following parameters:
    • The items() method returns a list of tuples with key-value pairs of the dictionary.
    • A key parameter specifies a lambda function that extracts the Kth index value of each value list using the indexing syntax x[1][K].
    • Assign the resulting sorted list to a variable named res.
  • Finally, print the sorted dictionary using print(“The sorted dictionary : ” + str(dict(res))). The dict() function converts the list of tuples back into a dictionary.

Python3




# Python3 code to demonstrate working of
# Sort Dictionary by Kth Index Value
# Using itemgetter() from operator module
 
# import required module
from operator import itemgetter
 
# initializing dictionary
test_dict = {'gfg': [5, 6, 7],
             'is': [1, 4, 7],
             'best': [8, 3, 1]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing K
K = 1
 
# Sort Dictionary by Kth Index Value
# Using itemgetter() from operator module
res = sorted(test_dict.items(), key=lambda x: x[1][K])
 
# printing result
print("The sorted dictionary : " + str(dict(res)))


Output

The original dictionary is : {'gfg': [5, 6, 7], 'is': [1, 4, 7], 'best': [8, 3, 1]}
The sorted dictionary : {'best': [8, 3, 1], 'is': [1, 4, 7], 'gfg': [5, 6, 7]}

Time complexity: O(nlog(n)), where n is the number of key-value pairs in the dictionary. 
Auxiliary space: O(n), where n is the number of key-value pairs in the dictionary. 

Using list comprehension + sorted() function with the key argument

Step-by-step approach:

  1. Initialize the dictionary test_dict.
  2. Print the original dictionary.
  3. Initialize the variable K to the desired index to sort by.
  4. Use the sorted() function with the key argument to sort the dictionary by the value at index K.
  5. The key function takes a lambda that returns the value to sort by, which in this case is the value at index K.
  6. The sorted() function returns a list of tuples, where each tuple contains the key-value pair from the original dictionary.
  7. Use dictionary comprehension to convert the sorted list of tuples back into a dictionary.
  8. The comprehension iterates over the sorted list of tuples and creates a new dictionary with the same keys and values.
  9. Print the sorted dictionary.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Sort Dictionary by Kth Index Value
 
# initializing dictionary
test_dict = {'gfg': [5, 6, 7],
             'is': [1, 4, 7],
             'best': [8, 3, 1]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing K
K = 1
 
# Sort Dictionary by Kth Index Value
res = {k: v for k, v in sorted(test_dict.items(), key=lambda item: item[1][K])}
 
# printing result
print("The sorted dictionary : " + str(res))


Output

The original dictionary is : {'gfg': [5, 6, 7], 'is': [1, 4, 7], 'best': [8, 3, 1]}
The sorted dictionary : {'best': [8, 3, 1], 'is': [1, 4, 7], 'gfg': [5, 6, 7]}

Time complexity: O(n log n), where n is the length of the dictionary. This is because we are using the sorted() function, which has a time complexity of O(n log n).
Auxiliary space: O(n), where n is the length of the dictionary. This is because we are creating a new dictionary to store the sorted key-value pairs.

Sort a Dictionary by Kth Index Value Using collections.OrderedDict() and heapq.nsmallest()

Use collections.OrderedDict() to create an ordered dictionary from the given dictionary and heapq.nsmallest() to get the smallest Kth index value.

Step-by-step approach:

  • Import the collections and heapq modules.
  • Initialize the given dictionary.
  • Initialize K, the index at which the dictionary should be sorted.
  • Create an ordered dictionary using collections.OrderedDict() and the given dictionary.
  • Use the heapq.nsmallest() function to get the smallest Kth index value.
  • Sort the ordered dictionary using the sorted() function and the Kth index value.
  • Return the sorted dictionary.

Below is the implementation of the above approach:

Python3




# importing modules
import collections
import heapq
 
# initializing dictionary
test_dict = {'gfg': [5, 6, 7],
             'is': [1, 4, 7],
             'best': [8, 3, 1]}
 
# initializing K
K = 1
 
# create ordered dictionary
ordered_dict = collections.OrderedDict(sorted(test_dict.items()))
 
# get smallest Kth index value
smallest = heapq.nsmallest(1, range(len(list(ordered_dict.values())[0])), key=lambda i: list(ordered_dict.values())[0][i])[0]
 
# sort ordered dictionary by Kth index value
sorted_dict = collections.OrderedDict(sorted(ordered_dict.items(), key=lambda x: x[1][smallest]))
 
# print sorted dictionary
print("The sorted dictionary : " + str(sorted_dict))


Output

The sorted dictionary : OrderedDict([('best', [8, 3, 1]), ('gfg', [5, 6, 7]), ('is', [1, 4, 7])])

Time complexity: O(n*logn), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), where n is the number of key-value pairs in the dictionary.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads