Python - Sort list of Single Item dictionaries according to custom ordering
Last Updated :
28 Apr, 2023
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
# 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
# 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
- Define two lists test_list1 and test_list2 containing some elements.
- 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.
- Sort the list of tuples tuple_list based on the key order using sorted() and lambda function as the key.
- 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.
- Print the final result sorted_dict_list.
- 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
# 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))
OutputThe 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)
Similar Reads
Sorting List of Dictionaries in Descending Order in Python The task of sorting a list of dictionaries in descending order involves organizing the dictionaries based on a specific key in reverse order. For example, given a list of dictionaries like a = [{'class': '5', 'section': 3}, {'Class': 'Five', 'section': 7}, {'Class': 'Five', 'section': 2}], the goal
3 min read
Python - Sort list according to other list order Sorting a list based on the order defined by another list is a common requirement in Python, especially in scenarios involving custom sorting logic. This ensures that elements in the first list appear in the exact order specified in the second list. Python provides various methods to accomplish this
2 min read
Python - Convert Dictionaries List to Order Key Nested dictionaries Given list of dictionaries, our task is to convert a list of dictionaries into a dictionary where each key corresponds to the index of the dictionary in the list and the value is the dictionary itself. For example: consider this list of dictionaries: li = [{"Gfg": 3, 4: 9}, {"is": 8, "Good": 2}] the
3 min read
Python | Sort given list of dictionaries by date Given a list of dictionary, the task is to sort the dictionary by date. Let's see a few methods to solve the task. Method #1: Using naive approach Python3 # Python code to demonstrate # sort a list of dictionary # where value date is in string # Initialising list of dictionary ini_list = [{'name':'a
2 min read
Sort a List of Dictionaries by a Value of the Dictionary - Python We are given a list of dictionaries where each dictionary contains multiple key-value pairs and our task is to sort this list based on the value of a specific key. For example, Given the list: students = [{'name': 'David', 'score': 85}, {'name': 'Sophia', 'score': 92}, {'name': 'Ethan', 'score': 78}
2 min read
Python - Sorted order Dictionary items pairing Sometimes, while working with Python dictionaries, we can have problem in which we need to perform reordering of dictionary items, to pair key and values in sorted order, smallest pairing to smallest value, largest to largest value and so on. This kind of application can occur in competitive domain
3 min read
Sort a List of Python Dictionaries by a Value Sorting a list of dictionaries by a specific value is a common task in Python programming. Whether you're dealing with data manipulation, analysis, or simply organizing information, having the ability to sort dictionaries based on a particular key is essential. In this article, we will explore diffe
3 min read
How to Convert a List into Ordered Set in Python? The task is to turn a list into an ordered set, meaning we want to remove any duplicate items but keep the order in which they first appear. In this article, we will look at different ways to do this in Python.Using OrderedDict.fromkeys()OrderedDict.fromkeys() method removes duplicates from a list a
2 min read
Python - Group single item dictionaries into List values Given a List of single-item dictionaries, group them into dictionary value lists according to similar values. Input : [{"Gfg" : 3}, {"is": 8}, {"Gfg": 18}, {"Best": 33}]Output : {'Gfg': [3, 18], 'is': [8], 'Best': [33]} Explanation : Each key converted to list values and dictionary. Input : [{"Gfg"
6 min read
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