In this python dictionary program, we will sort a dictionary using values.
Steps to solve the program
- Take a dictionary as input.
- Use for loop to iterate over keys and values of the dictionary by using dictionary.items() and also use sorted() method.
- Use the lambda function to sort the dictionary by values
- Use value as the key to sort the dictionary in the sorted() method.
- 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}