Algorithm
-
Input: Take a dictionary as input.
-
Sort Dictionary:
- Use the
sorted()
function with thekey
parameter. - The
key
parameter is set to a lambda function that extracts the values of the dictionary items. - This results in a list of sorted key-value pairs based on their values.
- Use the
-
Convert to Dictionary:
- Use the
dict()
constructor to convert the sorted list of key-value pairs back into a dictionary.
- Use the
-
Output: The sorted dictionary.
Code Examples
#1 Code Example- Sort the dictionary based on values
Code -
Python Programming
dt = {5:4, 1:6, 6:3}
sorted_dt = {key: value for key, value in sorted(dt.items(), key=lambda item: item[1])}
print(sorted_dt)
Copy The Code &
Try With Live Editor
Output
{6: 3, 5: 4, 1: 6}
#2 Code Example- Sort only the values
Code -
Python Programming
dt = {5:4, 1:6, 6:3}
sorted_dt_value = sorted(dt.values())
print(sorted_dt_value)
Copy The Code &
Try With Live Editor
Output
[3, 4, 6]
Demonstration
Python Programing Example to Sort a Dictionary by Value-DevsEnv