python-basics
python-basics copied to clipboard
Create sort_dict_by_value.py
Write a program to sort dictionary as per values
- In this program first we define a dictionary with key value pair which are unsorted order
- used a sorted() function for sorting dictionary as per values and create a new sorted dictionary
Define an unsorted dictionary
unsorted_dict = { 'apple': 3, 'banana': 1, 'cherry': 5, 'date': 2, 'elderberry': 4 }
Sort the dictionary by its values and create a new sorted dictionary
sorted_dict = dict(sorted(unsorted_dict.items(), key=lambda item: item[1]))
Print the sorted dictionary
print("Sorted Dictionary:", sorted_dict)