Python – Sort Dictionary List by Key’s ith Index value
Last Updated :
09 Apr, 2023
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
test_list = [{ "Gfg" : "Best" , "for" : "Geeks" },
{ "Gfg" : "Good" , "for" : "Me" },
{ "Gfg" : "Better" , "for" : "All" }]
print ( "The original list : " + str (test_list))
K = "Gfg"
i = 2
res = sorted (test_list, key = lambda sub: sub[K][i])
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
test_list = [{ "Gfg" : "Best" , "for" : "Geeks" },
{ "Gfg" : "Good" , "for" : "Me" },
{ "Gfg" : "Better" , "for" : "All" }]
print ( "The original list : " + str (test_list))
K = "Gfg"
i = 2
res = sorted (test_list, key = lambda sub: sub.get(K)[i])
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:
- Import the operator module.
- Initialize the value of K and i.
- Sort the dictionary list using the sorted() function, where key parameter is set to operator.itemgetter(K)[i].
- Print the sorted list.
Python3
import operator
test_list = [{ "Gfg" : "Best" , "for" : "Geeks" },
{ "Gfg" : "Good" , "for" : "Me" },
{ "Gfg" : "Better" , "for" : "All" }]
print ( "The original list : " + str (test_list))
K = "Gfg"
i = 2
res = sorted (test_list, key = lambda x: x.get(K)[i] if len (x.get(K)) > i else '')
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:
- Define a custom function named sort_dict_list_by_key_ith_index that takes three parameters: a list of dictionaries, the key to sort by, and the index of the key’s value to sort by.
- In the sort_dict_list_by_key_ith_index function, use the sorted() function with a lambda function to sort the list of dictionaries by the key’s ith index value.
- Return the sorted list of dictionaries.
- Call the sort_dict_list_by_key_ith_index function with the test_list, ‘Gfg‘, and 2 as the arguments.
- Print the sorted list of dictionaries.
Below is the implementation of the above approach:
Python3
test_list = [{ "Gfg" : "Best" , "for" : "Geeks" },
{ "Gfg" : "Good" , "for" : "Me" },
{ "Gfg" : "Better" , "for" : "All" }]
print ( "The original list : " + str (test_list))
def sort_dict_list_by_key_ith_index(lst, key, i):
return sorted (lst, key = lambda x: x[key][i])
sorted_list = sort_dict_list_by_key_ith_index(test_list, 'Gfg' , 2 )
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:
- Define a function that takes the list of dictionaries, the key, and the ith index value as arguments.
- Use a list comprehension to create a list of tuples containing the ith index value of the key and the corresponding dictionary.
- Use the sorted() function to sort the list of tuples based on the ith index value of the key.
- Use another list comprehension to extract only the dictionaries from the sorted list of tuples.
- Return the sorted list of dictionaries.
- Call the function by passing the list of dictionaries, the key, and the ith index value as arguments.
- Print the sorted list of dictionaries.
Below is the implementation of the above approach:
Python3
test_list = [{ "Gfg" : "Best" , "for" : "Geeks" },
{ "Gfg" : "Good" , "for" : "Me" },
{ "Gfg" : "Better" , "for" : "All" }]
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
sorted_list = sort_dict_list_by_key_ith_index(test_list, 'Gfg' , 2 )
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).
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...