Python Program to Sort a Dictionary by Value – 2022

Machine Learning Projects

Hey guys, in this blog we will see a Python Program to Sort a Dictionary by Value.

Example 1: Sort the dictionary based on values

# Python Program to Sort a Dictionary by Value

dt = {8:9, 2:4, 1:6, 3:3}

sorted_dt = {key: value for key, value in sorted(dt.items(), key=lambda item: item[1])}

print(sorted_dt)

Output

{3: 3, 2: 4, 1: 6, 8: 9}
  • In this method, we are sorting our dictionary on the basis of values (not keys).
  • We have used the sorted() function to sort our dictionary and the key to sort on is the second item in the tuple we will get using dt.items().
  • dt.items() will return dict_items([(8, 9), (2, 4), (1, 6), (3, 3)])
  • After using sorted on the above list we will get [(3,3),(2,4),(1,6),(8,9)]

Example 2: Sort only the values

# Python Program to Sort a Dictionary by Value

dt = {8:9, 2:4, 1:6, 3:3}

print(sorted(dt.values()))

Output

[3, 4, 6, 9]
  • In this method, we are only sorting and printing the values of dt(our Python Dictionary).
  • We have used the sorted() method on dt.values().
  • dt.values() is used to return all the values of the dictionary.
  • In this case, it will return [9,4,6,3].

Check out our other python programming examples

Leave a Comment

Your email address will not be published. Required fields are marked *