python-basics icon indicating copy to clipboard operation
python-basics copied to clipboard

Create sort_dict_by_value.py

Open ashishmeshram844 opened this issue 1 year ago • 1 comments

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

ashishmeshram844 avatar Mar 22 '24 07:03 ashishmeshram844

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)

lostxmusafir avatar Aug 03 '24 13:08 lostxmusafir