π Day 75/150 – Sort Dictionary by Values in Python
Dictionaries often store important data such as marks, prices, salaries, or scores. Sometimes, instead of sorting by keys, you may want to sort the dictionary based on its values.
Let's explore different ways to sort a dictionary by values in Python.
πΉ Method 1 – Using sorted() with lambda
The most common approach is to use sorted() along with a lambda function.
student = { "John": 85, "Alice": 92, "Bob": 78 } sorted_data = dict( sorted(student.items(), key=lambda item: item[1]) ) print(sorted_data)
Output
{'Bob': 78, 'John': 85, 'Alice': 92}
Explanation
- items() returns key-value pairs.
- item[1] refers to the value.
- sorted() arranges pairs according to values.
πΉ Method 2 – Sorting in Descending Order
To sort from highest to lowest value:
student = { "John": 85, "Alice": 92, "Bob": 78 } sorted_data = dict( sorted(student.items(), key=lambda item: item[1], reverse=True) ) print(sorted_data)
Output
{'Alice': 92, 'John': 85, 'Bob': 78}
Explanation
- reverse=True sorts values in descending order.
πΉ Method 3 – Using Function
def sort_by_values(data): return dict( sorted(data.items(), key=lambda item: item[1]) ) marks = { "Math": 90, "English": 80, "Science": 95 } print(sort_by_values(marks))
Output
{'English': 80, 'Math': 90, 'Science': 95}
Explanation
- Encapsulates sorting logic inside a reusable function.
πΉ Method 4 – Taking User Dictionary
data = { "apple": 50, "banana": 20, "mango": 35 } sorted_data = dict( sorted(data.items(), key=lambda item: item[1]) ) print(sorted_data)
Output
{'banana': 20, 'mango': 35, 'apple': 50}
Explanation
- Useful for sorting product prices, quantities, scores, etc.
π― Real-World Uses
✅ Ranking students by marks
✅ Sorting products by price
✅ Displaying leaderboard scores
✅ Organizing sales reports
✅ Analyzing frequency counts
π‘ Pro Tip
To get the highest-value item:
student = {"John": 85,
"Alice": 92,
"Bob": 78
}
highest = max(student.items(), key=lambda item: item[1])
print(highest)
Output
('Alice', 92)
π₯ Key Takeaways
✔️ Use sorted(dictionary.items(), key=lambda item: item[1]) to sort by values.
✔️ item[1] refers to dictionary values.
✔️ reverse=True sorts in descending order.
✔️ dict() converts sorted pairs back into a dictionary.
✔️ Sorting by values is common in ranking and reporting applications.


0 Comments:
Post a Comment