/  Technology   /  How to sort a list of dictionaries by the value of the dictionary?

How to sort a list of dictionaries by the value of the dictionary?

We can sort a list of dictionaries by their values using the inbuilt sorted() function. 

This function returns a sorted list of the specified iterable object. We can specify the sorting to be either ascending or descending order. Strings get sorted alphabetically, and numbers get sorted numerically.

We’ll now pass this list which has dictionaries and their keys to the sorted() method. We can pass these keys by using two different methods:

1.Using lambda() function

2.Using itemgetter method

 

Using lambda() function:

First, let us consider a list of dictionaries named ‘a’ with the following keys and values.

We’ll now pass this list using the sorted() function and pass the keys using the lambda function where we access the values of the dictionary using the iterator item. 

So our complete code looks like this and when we print the list ‘a’, we get it sorted by the values of the dictionary.

If our necessity is to print it in reverse order, then we just add reverse=True in the sorted() function next to the lambda() function separated by a comma.

 

Using itemgetter method:

Let’s take the similar example as above, i.e. list of dictionaries a. Now to use this item getter method, we’ll first have to import this from the operator module. 

The overall output of this is similar to that of the above-mentioned sorted() with lambda() function but its internal working slightly changes. This method converts the keys of the dictionary into tuples and then performs the sorting.

 

Note: This method is faster and comparatively efficient.

Leave a comment