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

Sorting list of dictionaries by custom order

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

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.

 

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.

Leave a comment