How to Sort Dictionary Keys by Values in Python?

Estimated read time 2 min read

To sort dictionary keys by values in Python, you can use the built-in sorted() function along with a lambda function that specifies the sorting key. Here’s an example implementation:

# Define a dictionary
my_dict = {'apple': 5, 'banana': 2, 'cherry': 7, 'date': 1, 'elderberry': 3}

# Sort the dictionary keys by their values
sorted_keys = sorted(my_dict, key=lambda k: my_dict[k])

# Print the sorted keys
print(sorted_keys)  # Output: ['date', 'banana', 'elderberry', 'apple', 'cherry']

In this example, we define a dictionary my_dict with string keys and integer values. We use the sorted() function to sort the dictionary keys based on their values. The lambda function lambda k: my_dict[k] specifies that the sorting key should be the corresponding value in the dictionary for each key. We then assign the sorted keys to the sorted_keys variable and print the result.

Note that the sorted() function returns a list of the sorted keys, not a sorted dictionary. If you want to create a sorted dictionary, you can iterate over the sorted keys and create a new dictionary with the sorted key-value pairs, like this:

# Create a sorted dictionary
sorted_dict = {}
for key in sorted_keys:
    sorted_dict[key] = my_dict[key]

# Print the sorted dictionary
print(sorted_dict)  # Output: {'date': 1, 'banana': 2, 'elderberry': 3, 'apple': 5, 'cherry': 7}

In this example, we iterate over the sorted keys and create a new dictionary sorted_dict with the same key-value pairs as my_dict, but with the keys sorted by their values. We then print the sorted dictionary.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply