Python Sort Dict by Value featured image

Python Sort Dict by Value : Stepwise Implementation

We can implement python sort dict by value using Using sorted()  function with lambda expression and Counter from collections module  easily. In this article, We will explore both methods with implementation step by step.Before we start the discussion, Lets have look for prerequesties.

Prerequesties :

Lets create a dictionary object with some data in random order.We will use the same dict object through out this article for implementation.

dict_obj = {Key1: 2, Key2: 4, Key3: 3, Key4: 1, Key5: 0}

Here the values are in random orders.

Method 1 : Using sorted() with lambda-

Case 1: When Python version is 3.7+

We can sort dict by value using lambda function with sorted() with Python version is 3.7+. Here is the code.

obj_sorted={k: v for k, v in sorted(dict_obj.items(), key=lambda item: item[1])}
print(obj_sorted)

In the above code the lambda function iterates over the dict and then sort it. After sorting it reconstruct the dict object and return it.

sort dict by value using lambda
sort dict by value using lambda

Case 2: When Python < 3.7 version –

Actually, dict object started preserving order after python 3.7 +version. Hence the above code will not work in lower python version.

import operator
obj_sorted = sorted(dict_obj.items(), key=operator.itemgetter(1))
print(dict(obj_sorted))

Well, you can see before printing the final obj_sorted we need to typecast it into dict object. We we do not do it, It will be a sorted list of tuples.

Note –

We can sort dict by value in reverse order by setting reverse=True in the sorted(). Here is the below syntax.

dict_obj = {"Key1": 2, "Key2": 4, "Key3": 3, "Key4": 1, "Key5": 0}
dict_obj_sorted={k: v for k, v in sorted(dict_obj.items(), key=lambda item: item[1],reverse=True)}
print(dict_obj_sorted)

Method 2 : Using Counter module –

This method has a limitation It will only sort the dict in ascending order by values. The reason is very clear that we are using Counter. This Count has a inbuilt function most_common(). This function returns the sorted list of tuples.

from collections import Counter
order_obj = Counter(dict_obj)
order_obj.most_common()

We can typecast it in dict object. Lets see how.

sort dict by value using Counter
sort dict by value using Counter

 

I hope the above methods must help you in sorting the dict using values. If you know more methods to achieve the same apart from the two, Please let us know in comment.

Thanks

Data Science Learner Team

 

 

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner