Q&A

Questions &
Answers with MarsDevs

HTML & CSS
JavaScript

How do I sort a dictionary by value?

Solution:

A dictionary in Python is a large structure that is, by default, unordered. So, to make queries easier, you should sort dictionaries by key or value. But it’s never easy. So, let’s learn together. To sort a dictionary by its values in Python, we always use the sorted() function. Here's an example.


my_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 1}

#sorting the dictionary by values
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))

#Print the sorted dictionary
print(sorted_dict)

My_dict.items() gives a list of key-value pairs in this example, and the key=lambda item: item[1] indicates that the sorting should be based on the values (item[1]). The output is a sorted list of tuples that is then turned back into a dictionary using dict().

The output will look like {'grape': 1, 'banana': 2, 'apple': 5, 'orange': 8}. However, this sorts the dictionary by values in ascending order. Want to sort in descending order? Try incorporating the reverse=True model in the sorted() function.


sorted_dict_desc = dict(sorted(my_dict.items(), key= lambda item: item[1], reverse = True))
print(sorted_dict_desc)

Then the output will look like this:

{'orange': 8, 'apple': 5, 'banana': 2, 'grape': 1}

Check out more about Python programming in our blogs!