Skip to main content

How to sort a dictionary by value in Python

How to sort a dictionary by value in Python.

Here's a step-by-step tutorial on how to sort a dictionary by value in Python:

Step 1: Create a dictionary

Start by creating a dictionary with key-value pairs. For example:

my_dict = {'apple': 5, 'banana': 2, 'cherry': 7, 'date': 3}

Step 2: Use the sorted() function with a lambda function

To sort the dictionary by its values, you can use the sorted() function. However, dictionaries are not directly sortable, so you need to pass a lambda function as the key argument to specify that you want to sort by values. The lambda function should take a single argument (the dictionary item) and return the value. Here's an example:

sorted_dict = sorted(my_dict.items(), key=lambda x: x[1])

The items() method returns a list of the dictionary's key-value pairs. By passing this list to the sorted() function and using the lambda function key=lambda x: x[1], you are telling Python to sort the dictionary based on the second element (value) of each key-value pair.

Step 3: Convert the sorted list back to a dictionary

The sorted_dict variable now contains a sorted list of key-value pairs from the dictionary. To convert it back to a dictionary, you can use a dictionary comprehension. Here's an example:

sorted_dict = {k: v for k, v in sorted_dict}

This creates a new dictionary where the keys and values are extracted from the sorted list.

Step 4: Print the sorted dictionary

Finally, you can print the sorted dictionary to see the results:

print(sorted_dict)

Here's the complete code:

my_dict = {'apple': 5, 'banana': 2, 'cherry': 7, 'date': 3}
sorted_dict = sorted(my_dict.items(), key=lambda x: x[1])
sorted_dict = {k: v for k, v in sorted_dict}
print(sorted_dict)

This will output:

{'banana': 2, 'date': 3, 'apple': 5, 'cherry': 7}

Congratulations! You have successfully sorted a dictionary by its values in Python.