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
# 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
# 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:
- 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
# 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))
OutputThe 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
# 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))
OutputThe 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
# 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))
OutputList 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).
Similar Reads
Python - Sort dictionaries list by Key's Value list index Given list of dictionaries, sort dictionaries on basis of Key's index value. Input : [{"Gfg" : [6, 7, 8], "is" : 9, "best" : 10}, {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19}, {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}], K = "Gfg", idx = 0 Output : [{'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [
14 min read
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
4 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
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
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