Python program to sort a dictionary using values.

In this python dictionary program, we will sort a dictionary using values.

Steps to solve the program
  1. Take a dictionary as input.
  2. Use for loop to iterate over keys and values of the dictionary by using dictionary.items() and also use sorted() method.
  3. Use the lambda function to sort the dictionary by values
  4. Use value as the key to sort the dictionary in the sorted() method.
  5. Print the output.
				
					dict1 = {'d':14,'b':52,'a':13,'c': 1}

sorted_ = {key: value for key, value in 
             sorted(dict1.items(), key=lambda item: item[1])}
print(sorted_)
				
			

Output :

				
					{'c': 1, 'a': 13, 'd': 14, 'b': 52}
				
			

sort a dictionary in python using keys.

add a key in a dictionary.

Leave a Comment