π Day 74/150 – Sort Dictionary by Keys in Python
Dictionaries are one of the most commonly used data structures in Python. Sometimes, you may want to display or process dictionary data in a sorted order based on its keys. Python provides several simple ways to achieve this.
Let's explore four different methods to sort a dictionary by its keys.
πΉ Method 1 – Using sorted()
The sorted() function returns the dictionary keys in alphabetical order.
student = { "name": "John", "age": 20, "course": "Python" } for key in sorted(student): print(key, ":", student[key])
Output
age : 20
course : Python
name : John
Explanation
- sorted(student) sorts all keys alphabetically.
- We then access each value using student[key].
πΉ Method 2 – Creating a Sorted Dictionary
You can create an entirely new dictionary with keys already sorted.
student = { "name": "John", "age": 20, "course": "Python" } sorted_dict = {key: student[key] for key in sorted(student)} print(sorted_dict)
Output
{'age': 20, 'course': 'Python', 'name': 'John'}
Explanation
- Dictionary comprehension creates a new dictionary.
- Keys are inserted in sorted order.
πΉ Method 3 – Using dict(sorted())
A concise and commonly used approach.
student = { "name": "John", "age": 20, "course": "Python" } sorted_dict = dict(sorted(student.items())) print(sorted_dict)
Output
{'age': 20, 'course': 'Python', 'name': 'John'}
Explanation
- items() returns key-value pairs.
- sorted() sorts those pairs by key.
- dict() converts the sorted list back into a dictionary.
πΉ Method 4 – Using Another Dictionary
Works for any dictionary data.
data = { "banana": 3, "apple": 5, "mango": 2 } sorted_data = dict(sorted(data.items())) print(sorted_data)
Output
{'apple': 5, 'banana': 3, 'mango': 2}
Explanation
- Keys are sorted alphabetically.
- Useful when working with real-world datasets.
π― When to Use Which Method?
| Method | Best Use Case |
|---|---|
| sorted() | Display keys in sorted order |
| Dictionary Comprehension | Create a new sorted dictionary |
| dict(sorted()) | Clean and concise solution |
| User Dictionary Example | Practical real-world sorting |
π‘ Pro Tip
To sort a dictionary in reverse alphabetical order, use:
{'mango': 2, 'banana': 3, 'apple': 5}sorted_dict = dict(sorted(data.items(), reverse=True))
Output
✅ Sorting dictionaries by keys is a useful skill when displaying reports, organizing data, or preparing outputs for users. Python's built-in sorted() function makes the task simple and efficient.


0 Comments:
Post a Comment