How to sort a dictionary by value in Python?


In Python, you can sort a dictionary by its values using the sorted function with a lambda function as the key.

Here’s an example:

my_dict = {“apple”: 2, “banana”: 4, “orange”: 1, “kiwi”: 3}

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



{‘orange’: 1, ‘apple’: 2, ‘kiwi’: 3, ‘banana’: 4}

In this example, we first use the items() method to get a list of (key, value) pairs from the dictionary. Then we pass this list to the sorted function along with a lambda function that extracts the second element (the value) of each tuple as the sorting key. Finally, we convert the sorted list of tuples back into a dictionary using the dict() constructor.

Note that by default, sorted sorts the list in ascending order. If you want to sort the dictionary in descending order, you can pass the reverse=True argument to sorted.

  • You must to post comments
Showing 0 results
Your Answer

Please first to submit.