To sort a dictionary by values in Python, you can use the `sorted()` function and a dictionary comprehension. This allows you to create a new dictionary with the key-value pairs sorted by value.
We can sort a dictionary by values in Python using the `sorted()` function and a dictionary comprehension. This example demonstrates how to declare and initialize a dictionary, use the `sorted()` function to sort the dictionary by values, and print the sorted dictionary.
For example,
my_dict
with integer keys and string values.my_dict = {
1: 'One',
2: 'Two',
3: 'Three'
}
# Sort the dictionary by values using sorted()
sorted_dict = {k: v for k, v in sorted(my_dict.items(), key=lambda item: item[1])}
# Print the sorted dictionary
print('Sorted dictionary:')
for key, value in sorted_dict.items():
print(f'Key: {key}, Value: {value}')
Sorted dictionary: Key: 1, Value: One Key: 3, Value: Three Key: 2, Value: Two
We can sort a dictionary by values in descending order in Python using the `sorted()` function and a dictionary comprehension with the `reverse=True` parameter. This example demonstrates how to declare and initialize a dictionary, use the `sorted()` function to sort the dictionary by values in descending order, and print the sorted dictionary.
For example,
my_dict
with integer keys and string values.my_dict = {
1: 'One',
2: 'Two',
3: 'Three'
}
# Sort the dictionary by values in descending order using sorted()
sorted_dict = {k: v for k, v in sorted(my_dict.items(), key=lambda item: item[1], reverse=True)}
# Print the sorted dictionary
print('Sorted dictionary:')
for key, value in sorted_dict.items():
print(f'Key: {key}, Value: {value}')
Sorted dictionary: Key: 2, Value: Two Key: 3, Value: Three Key: 1, Value: One
In this tutorial, we learned How to Sort a Dictionary by Values in Python language with well detailed examples.