Sorting a dictionary by value allows you to arrange the key-value pairs in a specific order based on the values. In this blog post, we will explore different methods to sort a dictionary by value in ascending or descending order in Python.
Method 1: Using the sorted() function with a lambda function
# Method 1: Using the sorted() function with a lambda function my_dict = {"a": 10, "b": 5, "c": 20, "d": 15} sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1])) print("Ascending Order:", sorted_dict) sorted_dict_desc = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True)) print("Descending Order:", sorted_dict_desc)
Output:
Ascending Order: {‘b’: 5, ‘a’: 10, ‘d’: 15, ‘c’: 20}
Descending Order: {‘c’: 20, ‘d’: 15, ‘a’: 10, ‘b’: 5}
Method 2: Using the operator module
# Method 2: Using the operator module import operator my_dict = {"a": 10, "b": 5, "c": 20, "d": 15} sorted_dict = dict(sorted(my_dict.items(), key=operator.itemgetter(1))) print("Ascending Order:", sorted_dict) sorted_dict_desc = dict(sorted(my_dict.items(), key=operator.itemgetter(1), reverse=True)) print("Descending Order:", sorted_dict_desc)
Output:
Ascending Order: {‘b’: 5, ‘a’: 10, ‘d’: 15, ‘c’: 20}
Descending Order: {‘c’: 20, ‘d’: 15, ‘a’: 10, ‘b’: 5}