Sorting with Python's sorted() function using key

🧠 Python Concept: sorted() with key Sort smarter, not harder 😎 ❌ Traditional Way students = [ {"name": "Alice", "marks": 85}, {"name": "Bob", "marks": 92}, {"name": "Charlie", "marks": 78} ] # Sorting manually (messy & long) students.sort(key=lambda x: x["marks"]) print(students) ✅ Pythonic Way students = [ {"name": "Alice", "marks": 85}, {"name": "Bob", "marks": 92}, {"name": "Charlie", "marks": 78} ] sorted_students = sorted(students, key=lambda x: x["marks"]) print(sorted_students) 🧒 Simple Explanation Think of key like a rule for sorting 📏 ➡️ “Sort based on THIS value” ➡️ Python handles the rest 💡 Why This Matters ✔ Clean & readable ✔ No custom loops needed ✔ Works with complex data ✔ Very common in real-world apps ⚡ Bonus Tip (Reverse Order) sorted_students = sorted(students, key=lambda x: x["marks"], reverse=True) 🐍 Don’t just sort — sort smart 🐍 Let Python do the heavy lifting #Python #PythonTips #CleanCode #LearnPython #Sort #SortingWithKeys #Programming #DeveloperLife #100DaysOfCode

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories