You can sort a dictionary by its values in Python using the sorted() function along with a custom sorting key. Here's how you can do it:
python
# Sample dictionary
my_dict = {'apple': 3, 'banana': 1, 'cherry': 2, 'date': 4}
# Sort the dictionary by values in ascending order
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))
# Print the sorted dictionary
print(sorted_dict)
In this example:
We have a dictionary
my_dictwhere keys are fruits, and values are their corresponding quantities.We use the
sorted()function with theitems()method of the dictionary to convert it into a list of key-value pairs. Theitems()method returns a view of all items (key-value pairs) in the dictionary.We specify a custom sorting key using the
keyparameter of thesorted()function. In this case, we use a lambda functionlambda item: item[1]to sort the dictionary based on the values (item[1]represents the value of each key-value pair).The result of the
sorted()function is a list of sorted key-value pairs. We then convert this list back into a dictionary using thedict()constructor.Finally, we print the sorted dictionary, which will contain the same key-value pairs but sorted by their values in ascending order.
If you want to sort the dictionary in descending order, you can add the reverse=True parameter to the sorted() function:
python
# Sort the dictionary by values in descending order
sorted_dict_desc = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))
# Print the sorted dictionary in descending order
print(sorted_dict_desc)
This will sort the dictionary by values in descending order, with the highest values first.
Comments
Post a Comment