Algorithm


  1. Input: Take a dictionary as input.

  2. Sort Dictionary:

    • Use the sorted() function with the key 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.
  3. Convert to Dictionary:

    • Use the dict() constructor to convert the sorted list of key-value pairs back into a dictionary.
  4. 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

x
+
cmd
{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

x
+
cmd
[3, 4, 6]
Advertisements

Demonstration


Python Programing Example to Sort a Dictionary by Value-DevsEnv