Python Program - Sort a Dictionary by Value

here's a Python program that sorts a dictionary by value:

# Define a dictionary
my_dict = {"apple": 5, "banana": 2, "orange": 4, "pear": 1}

# Sort the dictionary by value using the sorted() function and a lambda function
sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1]))

# Print the sorted dictionary
print("Sorted dictionary:", sorted_dict)
Source:ww‮tfigi.w‬idea.com

In this program, we first define a dictionary called my_dict containing key-value pairs representing the number of fruits of each type.

We can sort the dictionary by value using the sorted() function and a lambda function. The sorted() function takes an iterable (in this case, the dictionary items), and returns a new list containing the elements of the iterable in sorted order.

The key parameter of the sorted() function is used to specify a function that takes an element of the iterable (in this case, a key-value pair of the dictionary), and returns a value that is used for sorting. We can use a lambda function to extract the value of each key-value pair, which is the second element of the tuple (x[1]).

We then use the dict() constructor to convert the sorted list of key-value pairs back into a dictionary.

Finally, we can print the sorted dictionary using the print() function. The output will be a dictionary sorted by value in ascending order:

Sorted dictionary: {'pear': 1, 'banana': 2, 'orange': 4, 'apple': 5}

If we wanted to sort the dictionary in descending order, we could use the reverse parameter of the sorted() function, like this:

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

This would sort the dictionary by value in descending order, resulting in the following output:

Sorted dictionary: {'apple': 5, 'orange': 4, 'banana': 2, 'pear': 1}