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

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

 

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.

 

Example:

a = [{"Num" : 3, "Square" : 9}, {"Num" : 2, "Square" :4 }, {"Num" : 5, "Square" : 25}, {"Num" :4, "Square" : 16}]

 

Output:

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. 

 

Example:

print(sorted(a, key = lambda item: item["Square"]))

 

Output:

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

 

Example:

a = [{"Num" : 3, "Square" : 9}, {"Num" : 2, "Square" :4 }, {"Num" : 5, "Square" : 25}, {"Num" :4, "Square" : 16}]
print(sorted(a, key = lambda item: item["Square"]))

 

Output:

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.

 

Example:

print(sorted(a, key = lambda item: item["Square"],reverse=True))

 

Output:

 

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.

 

Example:

from operator import itmgetter
a = [{"Num" : 3, "Square" : 9}, {"Num" : 2, "Square" :4 }, {"Num" : 5, "Square" : 25}, {"Num" :4, "Square" : 16}]
print(sorted(a, key = itemgetter("Square")))

 

Output:

 

Note: This method is faster and comparatively efficient.

Leave a comment