Sorting a dictionary by value is a common task in Python.
This can be achieved in a simple way using the built-in sorted() function and a lambda function.
Let’s say we have a dictionary with some key-value pairs:
my_dict = {'apple': 10, 'orange': 20, 'banana': 5, 'kiwi': 15}To sort this dictionary by its values, we can use the sorted() function as follows:
sorted_dict = sorted(my_dict.items(), key=lambda x: x[1])
Here, we are passing the my_dict.items() as the first argument to sorted() function which returns a list of tuples containing key-value pairs of the dictionary.
Then, we pass the key parameter to the sorted() function which takes a lambda function.
This lambda function extracts the second element of each tuple, which is the value, and uses it for sorting the dictionary.
Finally, the sorted() function returns a list of sorted tuples.
Now, if we print the sorted_dict, we will get the following output:
[('banana', 5), ('apple', 10), ('kiwi', 15), ('orange', 20)]As we can see, the dictionary is sorted by its values in ascending order.
If we want to sort the dictionary in descending order, we can simply pass the reverse=True parameter to the sorted() function, like this:
sorted_dict = sorted(my_dict.items(), key=lambda x: x[1], reverse=True)
Now, if we print the sorted_dict, we will get the following output:
[('orange', 20), ('kiwi', 15), ('apple', 10), ('banana', 5)]As we can see, the dictionary is sorted by its values in descending order.
In conclusion, sorting a dictionary by value in Python is a simple task that can be achieved using the sorted() function and a lambda function.
By understanding this concept, we can easily sort any dictionary by its values in both ascending and descending order.




