JS Problems geeksforgeeks Exercises and Solutions for Beginners

How to Sort a Dictionary by Value in Python [All Method]️

The step-by-step guide on this page will show you How to Sort a Dictionary by Value in Python. If you get stuck or have questions at any point,simply comment below.
Question: What is the best way to approach this problem? Answer: Check out this blog code to learn how to fix errors How to Sort a Dictionary by Value in Python. Question:”What should you do if you run into code errors?” Answer:”By following this blog, you can find a solution.”

Suppose we have a dictionary that contains unsorted values.

unsorted_dict = {
    "one": 1,
    "zero": 0,
    "three": 3,
    "two": 2
}

We want to sort this dictionary based on these values to get this resulting sorted dictionary.

sorted_dict = {
    "zero": 0,
    "one": 1,
    "two": 2,
    "three": 3
}

We can use the sorted() function to achieve this.

sorted_dict = dict(sorted(unsorted_dict.items(), key=lambda item: item[1]))
print(sorted_dict) # {'zero': 0, 'one': 1, 'two': 2, 'three': 3}

We can sort descending just by adding reverse=True.

sorted_dict = dict(sorted(unsorted_dict.items(), key=lambda item: item[1], reverse=True))
print(sorted_dict) # {'three': 3, 'two': 2, 'one': 1, 'zero': 0}

Finally, we can get the same ascending, sorted result using dictionary comprehension.

sorted_dict = {k: v for k, v in sorted(unsorted_dict.items(), key=lambda item: item[1])}
print(sorted_dict) # {'zero': 0, 'one': 1, 'two': 2, 'three': 3}


Now you learned, How you can use & How to Sort a Dictionary by Value in Python.
If you have any questions or get stuck, please dont hesitate to reach out to me for help.

Related Articles

Leave a Reply

Your email address will not be published.

Back to top button