python

How to Sort a Dictionary by Value in Python

In this tutorial, we are going to see how to sort a dictionary by Value in Python. A dictionary in Python is a very versatile and useful type of container, capable of storing a collection of values and retrieving them via keys.

Values can be objects of any type (dictionaries can even be nested within other dictionaries) and keys can be of any object as long as it’s hashable, which means it’s immutable. Unlike lists or tuples, key/value pairs in dictionaries don’t have a defined order, which means we can have a dictionary like this:

colors = {'blue': 2, 'red': 1, 'green': 4, 'orange': 3}
 

How to Sort a Dictionary by Value in Python

If we want to sort objects in a dictionary according to their values, the easiest way is to use Python’s “sorted” method with a lambda function, which takes any iterable and returns a list of sorted values (in ascending order by default).

names = {'carlos': 2, 'daoud': 1, 'bob': 4, 'alex': 3}

for k, v in sorted(names.items(), key=lambda x: x[1]):
    print("%s: %s" % (k, v))

Output:

daoud: 1
carlos: 2
alex: 3
bob: 4
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *