How to Sort a Dictionary by Value in Python

How to Sort a Dictionary by Value in Python

If you have a dictionary in Python and you want to sort it by value, there are a few steps you need to follow. Sorting a dictionary is a common task in Python programming, and it can be useful for a variety of applications. In this tutorial, we will walk you through the process of sorting a dictionary by value in Python.

Step 1: Create a Dictionary

First, you need to create a dictionary that you want to sort. For example, let’s say you have a dictionary that contains the number of medals won by different countries in the Olympics:

 medals = {'USA': 11348, 'Russia': 10034, 'Germany': 9326, 'UK': 8472, 'France': 8406}

Step 2: Sort the Dictionary by Value

To sort the dictionary by value, you need to use the sorted() function in Python. However, the sorted() function only works on lists, so you need to convert the dictionary into a list of tuples first. Each tuple will contain the key and value of each item in the dictionary.

 sorted_medals = sorted(medals.items(), key=lambda x: x[1])

In this example, we are using a lambda function to specify that we want to sort the list of tuples by the second element (i.e., the value) of each tuple. The sorted() function will return a new list of tuples that is sorted by value.

Step 3: Convert the Sorted List of Tuples back to a Dictionary

After sorting the list of tuples, you can convert it back to a dictionary using the dict() function in Python.

 sorted_medals_dict = dict(sorted_medals)

Now, sorted_medals_dict is a new dictionary that contains the same key-value pairs as the original dictionary, but the items are sorted by value.

Step 4: Print the Sorted Dictionary

Finally, you can print the sorted dictionary to verify that it has been sorted correctly.

 print(sorted_medals_dict)

This will output the following:

{'France': 8406, 'UK': 8472, 'Germany': 9326, 'Russia': 10034, 'USA': 11348}

Sorting a dictionary by value in Python is a simple process that involves converting the dictionary into a list of tuples, sorting the list by value using the sorted() function, and then converting the sorted list of tuples back to a dictionary.