Open In App

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’, ‘for’: ‘Me’}] 
Explanation : Sort in order of e = e < o, as 1st index element of “Gfg”‘s value. 



Input : [{“Gfg” : “Best”, “for” : “Geeks”}, {“Gfg” : “Good”, “for” : “Me”}, {“Gfg” : “Better”, “for” : “All”}], K = “Gfg”, i = 0 
Output : [{‘Gfg’: ‘Best’, ‘for’: ‘Geeks’}, {‘Gfg’: ‘Better’, ‘for’: ‘All’}, {‘Gfg’: ‘Good’, ‘for’: ‘Me’}] 
Explanation : Sort in order of B = B < G, as 1st index element of “Gfg”‘s value.

Method #1 : Using sort() + lambda



The combination of above functions can be used to solve this problem. In this, we perform task of sorting using sort() and lambda function in “key” parameter drives condition.




# Python3 code to demonstrate working of
# Sort Dictionary List by Key's ith Index value
# Using sort() + lambda
 
# initializing lists
test_list = [{"Gfg": "Best", "for": "Geeks"},
             {"Gfg": "Good", "for": "Me"},
             {"Gfg": "Better", "for": "All"}]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K
K = "Gfg"
 
# initializing i
i = 2
 
# using sort to perform sort(), lambda
# function drives conditions
res = sorted(test_list, key=lambda sub: sub[K][i])
 
# printing result
print("List after sorting : " + str(res))

Output

The original list : [{‘Gfg’: ‘Best’, ‘for’: ‘Geeks’}, {‘Gfg’: ‘Good’, ‘for’: ‘Me’}, {‘Gfg’: ‘Better’, ‘for’: ‘All’}] List after sorting : [{‘Gfg’: ‘Good’, ‘for’: ‘Me’}, {‘Gfg’: ‘Best’, ‘for’: ‘Geeks’}, {‘Gfg’: ‘Better’, ‘for’: ‘All’}]

Time Complexity: O(nlogn)
Auxiliary Space: O(1)

Method #2 : Using sort() + lambda + get()

The combination of above functions can also solve this problem. This is just a slight variation to above method. In this, we use get() to avoid chances of key not present in particular record.




# Python3 code to demonstrate working of
# Sort Dictionary List by Key's ith Index value
# Using sort() + lambda + get()
 
# initializing lists
test_list = [{"Gfg": "Best", "for": "Geeks"},
             {"Gfg": "Good", "for": "Me"},
             {"Gfg": "Better", "for": "All"}]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K
K = "Gfg"
 
# initializing i
i = 2
 
# using sort to perform sort(), lambda
# function drives conditions, get() used to
# avoid missing key error
res = sorted(test_list, key=lambda sub: sub.get(K)[i])
 
# printing result
print("List after sorting : " + str(res))

Output

The original list : [{‘Gfg’: ‘Best’, ‘for’: ‘Geeks’}, {‘Gfg’: ‘Good’, ‘for’: ‘Me’}, {‘Gfg’: ‘Better’, ‘for’: ‘All’}] List after sorting : [{‘Gfg’: ‘Good’, ‘for’: ‘Me’}, {‘Gfg’: ‘Best’, ‘for’: ‘Geeks’}, {‘Gfg’: ‘Better’, ‘for’: ‘All’}]

Time complexity: The time complexity of this Python code is O(nlogn), where n is the number of elements in the input list.
Auxiliary space: The auxiliary space used by this Python code is O(n), where n is the number of elements in the input list.

Method #3: Using operator.itemgetter()

We can also sort the dictionary list by key’s ith index value using the operator.itemgetter() function instead of using lambda and get() function.

Here are the steps to implement this method:

  1. Import the operator module.
  2. Initialize the value of K and i.
  3. Sort the dictionary list using the sorted() function, where key parameter is set to operator.itemgetter(K)[i].
  4. Print the sorted list.




# importing operator module
import operator
 
# initializing lists
test_list = [{"Gfg": "Best", "for": "Geeks"},
             {"Gfg": "Good", "for": "Me"},
             {"Gfg": "Better", "for": "All"}]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K
K = "Gfg"
 
# initializing i
i = 2
 
# sorting dictionary list using operator.itemgetter()
res = sorted(test_list, key=lambda x: x.get(K)[i] if len(x.get(K)) > i else '')
 
# printing result
print("List after sorting : " + str(res))

Output
The original list : [{'Gfg': 'Best', 'for': 'Geeks'}, {'Gfg': 'Good', 'for': 'Me'}, {'Gfg': 'Better', 'for': 'All'}]
List after sorting : [{'Gfg': 'Good', 'for': 'Me'}, {'Gfg': 'Best', 'for': 'Geeks'}, {'Gfg': 'Better', 'for': 'All'}]

Time complexity: O(nlogn), where n is the length of the list. In addition, operator.itemgetter() function has a time complexity of O(1). So, the overall time complexity is O(nlogn).
Auxiliary space: O(1), as we are not using any extra space other than the given list.

Method #5: Using a custom function

Step-by-step approach:

Below is the implementation of the above approach:




# Python3 code to demonstrate working of
# Sort Dictionary List by Key's ith Index value
# Using a custom function
 
# initializing lists
test_list = [{"Gfg": "Best", "for": "Geeks"},
             {"Gfg": "Good", "for": "Me"},
             {"Gfg": "Better", "for": "All"}]
 
# printing original list
print("The original list : " + str(test_list))
 
# define custom function to sort list of dictionaries by key's ith index value
def sort_dict_list_by_key_ith_index(lst, key, i):
    return sorted(lst, key=lambda x: x[key][i])
 
# sort the list of dictionaries by the ith index value of the key 'Gfg'
sorted_list = sort_dict_list_by_key_ith_index(test_list, 'Gfg', 2)
 
# print the sorted list of dictionaries
print("List after sorting : " + str(sorted_list))

Output
The original list : [{'Gfg': 'Best', 'for': 'Geeks'}, {'Gfg': 'Good', 'for': 'Me'}, {'Gfg': 'Better', 'for': 'All'}]
List after sorting : [{'Gfg': 'Good', 'for': 'Me'}, {'Gfg': 'Best', 'for': 'Geeks'}, {'Gfg': 'Better', 'for': 'All'}]

Time complexity: O(n log n), where n is the number of dictionaries in the list.
Auxiliary space: O(n), where n is the number of dictionaries in the list.

Method #6: Using a list comprehension and the sorted() function

Step:

  1. Define a function that takes the list of dictionaries, the key, and the ith index value as arguments.
  2. Use a list comprehension to create a list of tuples containing the ith index value of the key and the corresponding dictionary.
  3. Use the sorted() function to sort the list of tuples based on the ith index value of the key.
  4. Use another list comprehension to extract only the dictionaries from the sorted list of tuples.
  5. Return the sorted list of dictionaries.
  6. Call the function by passing the list of dictionaries, the key, and the ith index value as arguments.
  7. Print the sorted list of dictionaries.

Below is the implementation of the above approach:




# Python3 code to demonstrate working of
# Sort Dictionary List by Key's ith Index value
# Using a list comprehension and the sorted() function
 
# initializing lists
test_list = [{"Gfg": "Best", "for": "Geeks"},
             {"Gfg": "Good", "for": "Me"},
             {"Gfg": "Better", "for": "All"}]
 
# Function to sort list of
# dictionaries by key's ith index value
def sort_dict_list_by_key_ith_index(lst, key, i):
    sorted_tuples = sorted([(d[key][i], d) for d in lst])
    sorted_list = [d for _, d in sorted_tuples]
    return sorted_list
 
 
# sort the list of dictionaries by the
# ith index value of the key 'Gfg'
sorted_list = sort_dict_list_by_key_ith_index(test_list, 'Gfg', 2)
 
# print the sorted list of dictionaries
print("List after sorting : " + str(sorted_list))

Output
List after sorting : [{'Gfg': 'Good', 'for': 'Me'}, {'Gfg': 'Best', 'for': 'Geeks'}, {'Gfg': 'Better', 'for': 'All'}]

Time Complexity: O(n log n), where n is the number of dictionaries in the list.
Auxiliary Space: O(n), where n is the number of dictionaries in the list (for creating the list of tuples).


Article Tags :