How do I sort a dictionary by value?

 

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:

  1. We have a dictionary my_dict where keys are fruits, and values are their corresponding quantities.

  2. We use the sorted() function with the items() method of the dictionary to convert it into a list of key-value pairs. The items() method returns a view of all items (key-value pairs) in the dictionary.

  3. We specify a custom sorting key using the key parameter of the sorted() function. In this case, we use a lambda function lambda item: item[1] to sort the dictionary based on the values (item[1] represents the value of each key-value pair).

  4. The result of the sorted() function is a list of sorted key-value pairs. We then convert this list back into a dictionary using the dict() constructor.

  5. 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