/  Technology   /  Sorting list of dictionaries by custom order in Python
Datascience in car technology

Sorting list of dictionaries by custom order in Python

In the previous articles, we have discussed several ways of sorting dictionaries and lists of dictionaries. In this article, we’ll learn how to sort them in a custom order.

 

Let’s understand this by taking an example. We have two lists list_1 and list_2 in which the first list of dictionaries, list_1, is to be ordered in the order of elements in a custom manner given in the second list list_2

 

Example:

list_1= [{'by' : 3}, {"i2tutorials" : 2}, {"Python Programming" : 1}]
list_2 = [{"Python Programming", "by", "i2tutorials"]

 

Output:

We can achieve this by using two methods:

  • Using a combination of sorted(), index(), keys(),  lambda
  • Using a combination of sort(),  index(), keys(), lambda 

 

Using sorted(), index(), keys(),  lambda:

The sorted() function does the required sorting, the index() function helps to get the order from our custom list list_2 and the keys() function is used to get the keys from the dictionary present in the list of dictionaries list_1.

 

Example:

list_1= [{'by' : 3}, {'i2tutorials' : 2}, {'Python Programming' : 1}]
list_2 = [{'Python Programming', 'by', 'i2tutorials']

print("List 1 is : " + str(list_1))
print("List 2 is : " + str(list_2))

result = sorted(list_1, key = lambda i: list_2.index(list(i.keys())[0]))
print("The custom order list : " + str(result))

 

Output:

 

Using sort(), index(), keys(), lambda:

Here we use the sort() function instead of the sorted() function. The only difference between these is that sort() performs in-place sorting and doesn’t create and store the sorted order in a new list, like ‘result’ in the above example. 

All the other functions operate the same way as discussed.

 

Example:

list_1= [{'by' : 3}, {'i2tutorials' : 2}, {'Python Programming' : 1}]
list_2 = [{"Python Programming", 'by', 'i2tutorials']

print("List 1 is : " + str(list_1))
print("List 2 is : " + str(list_2))

result = sorted(list_1, key = lambda i: list_2.index(list(i.keys())[0]))
print("The custom order list : " + str(result))

 

Output:

Leave a comment