Skip to content

Conversation

@ashishmeshram844
Copy link
Contributor

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
sort a given dictionary according to values
@lostxmusafir
Copy link

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)

Copy link

@lostxmusafir lostxmusafir left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

@learning-zone learning-zone merged commit a28d9b2 into learning-zone:master Dec 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

5 participants