Skip to content

Create sort_dict_by_value.py - #16

Merged
learning-zone merged 1 commit into
learning-zone:masterfrom
ashishmeshram844:master
Dec 27, 2024
Merged

Create sort_dict_by_value.py#16
learning-zone merged 1 commit into
learning-zone:masterfrom
ashishmeshram844:master

Conversation

@ashishmeshram844

Copy link
Copy Markdown
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
Copy Markdown

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 lostxmusafir left a comment

Copy link
Copy Markdown

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants