Open In App

Python – Sort list of Single Item dictionaries according to custom ordering

Given single item dictionaries list and keys ordering list, perform sort of dictionary according to custom keys.

Input : test_list1 = [{‘is’ : 4}, {“Gfg” : 10}, {“Best” : 1}], test_list2 = [“Gfg”, “is”, “Best”] Output : [{‘Gfg’: 10}, {‘is’: 4}, {‘Best’: 1}] Explanation : By list ordering, dictionaries list get sorted. Input : test_list1 = [{“Gfg” : 10}, {‘is’ : 4}, {“Best” : 1}], test_list2 = [“Gfg”, “is”, “Best”] Output : [{‘Gfg’: 10}, {‘is’: 4}, {‘Best’: 1}] Explanation : Already ordered. No reordering required.



Method #1 : Using sorted() + index() + keys() + lambda 

The combination of above functionalities can be used to solve this problem. In this, we perform sort using sorted(), index() is used to get ordering from custom list, keys() used to extract the keys from dictionary.






# Python3 code to demonstrate working of
# Sort list of Single Item dictionaries according to custom ordering
# Using sorted() + index() + keys() + lambda
 
# initializing lists
test_list1 = [{'is' : 4}, {'for' : 7}, {"Gfg" : 10}, {"Best" : 1}, {"CS" : 8}]
test_list2 = ["Gfg", "is", "Best", "for", "CS"]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# sorted() used to perform sort(), returns the result
# to other variable, ordering handled using index() from order list
res = sorted(test_list1, key = lambda ele: test_list2.index(list(ele.keys())[0]))
 
# printing result
print("The custom order list : " + str(res))

Output

The original list 1 is : [{‘is’: 4}, {‘for’: 7}, {‘Gfg’: 10}, {‘Best’: 1}, {‘CS’: 8}] The original list 2 is : [‘Gfg’, ‘is’, ‘Best’, ‘for’, ‘CS’] The custom order list : [{‘Gfg’: 10}, {‘is’: 4}, {‘Best’: 1}, {‘for’: 7}, {‘CS’: 8}]

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

Method #2 : Using sort() + index() + keys() + lambda

This is yet another way in which this task can be performed. In this, we perform the task of sorting using sort(), performs inplace sorting, other constructs remain same.




# Python3 code to demonstrate working of
# Sort list of Single Item dictionaries according to custom ordering
# Using sort() + index() + keys() + lambda
 
# initializing lists
test_list1 = [{'is' : 4}, {'for' : 7}, {"Gfg" : 10}, {"Best" : 1}, {"CS" : 8}]
test_list2 = ["Gfg", "is", "Best", "for", "CS"]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# sort() used to perform inplace sort
test_list1.sort(key = lambda ele: test_list2.index(list(ele.keys())[0]))
 
# printing result
print("The custom order list : " + str(test_list1))

Output

The original list 1 is : [{‘is’: 4}, {‘for’: 7}, {‘Gfg’: 10}, {‘Best’: 1}, {‘CS’: 8}] The original list 2 is : [‘Gfg’, ‘is’, ‘Best’, ‘for’, ‘CS’] The custom order list : [{‘Gfg’: 10}, {‘is’: 4}, {‘Best’: 1}, {‘for’: 7}, {‘CS’: 8}]

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

Method 3 : use the built-in zip() function

  1. Define two lists test_list1 and test_list2 containing some elements.
  2. Create a list of tuples tuple_list using test_list1 and test_list2, where each tuple contains a single-item dictionary from test_list1 and its corresponding key order from test_list2.
  3. Sort the list of tuples tuple_list based on the key order using sorted() and lambda function as the key.
  4. Extract the sorted list of dictionaries sorted_dict_list by iterating through the sorted tuple list sorted_tuple_list and selecting the first element of each tuple.
  5. Print the final result sorted_dict_list.
  6. In summary, the program sorts a list of single item dictionaries based on a custom ordering specified by another list, by creating a list of tuples, sorting them based on the order of keys specified in the custom ordering list and then extracting the sorted




# Python3 code to demonstrate working of
# Sort list of Single Item dictionaries according to custom ordering
# Using zip() and sorted()
 
# initializing lists
test_list1 = [{'is' : 4}, {'for' : 7}, {"Gfg" : 10}, {"Best" : 1}, {"CS" : 8}]
test_list2 = ["Gfg", "is", "Best", "for", "CS"]
 
# create a list of tuples, each tuple contains a single-item dictionary and its corresponding key order
tuple_list = [(d, test_list2.index(list(d.keys())[0])) for d in test_list1]
 
# sort the list of tuples based on the key order
sorted_tuple_list = sorted(tuple_list, key=lambda x: x[1])
 
# extract the sorted list of dictionaries
sorted_dict_list = [x[0] for x in sorted_tuple_list]
 
# printing result
print("The custom order list : " + str(sorted_dict_list))

Output
The custom order list : [{'Gfg': 10}, {'is': 4}, {'Best': 1}, {'for': 7}, {'CS': 8}]

Time complexity: O(n log n) (due to the use of sorted())
Auxiliary space: O(n) (to store the list of tuples)


Article Tags :