Python

How to sort a dictionary by value in Python

March 25, 2022

How to sort a dictionary by value in Python

In this article, we’ll learn how to sort a dictionary by value with Python, using a feature of the language’s functional paradigm.

sort a dictionary by value thumb

Hey you programmer, ok? Let’s learn more about Python!

The idea here is very simple, let’s use a lambda function to access all the values in the dictionary, which is Python’s way of accessing complex objects

As this function goes through it, it identifies if an element has a value greater than the other through the sorted function and the lambda, which will be our second argument

Let’s see it in practice:

unordered = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}

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

print(sortedDict)

Check out the return:

{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

Note that the dictionary was ordered correctly by the values, the keys do not influence the order

If you need the order to be reversed, use the parameter reverse=True

See an example:

unordered = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}

sortedDict = {k: v for k, v in sorted(unordered.items(), key=lambda item: item[1], reverse=True)}

print(sortedDict)

This is the result:

{3: 4, 4: 3, 1: 2, 2: 1, 0: 0}

Once again, the dictionary was sorted by values only, now in reverse

Conclusion

In this article we arned how to sort a dictionary by value in Python

We use the sorted method, with a lambda function, which is Python’s way of accessing complete object values one by one

This way the dictionaries are sorted by their value, we can reverse the order using the reversed parameter set to True

Do you want to learn more about Python? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x