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]))
print(sorted_dict)
Output:
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
.
- sunny asked 1 month ago
- You must login to post comments
Please login first to submit.