How to Sort a Dictionary in Python
A robust data structure for storing key-value pairs is a Python dictionary. They are mutable, meaning their contents can be modified after creation. However, dictionaries are inherently unordered, which means the data is not stored in a specific sequence.
While a dictionary permits duplicate values, each key must be distinct. Dictionaries are declared using curly braces {}, with key-value pairs separated by commas.
Complete Python Course with Advance topics:-
Example:
student_info = {'name': 'Devansh', 'age': 22, 'Rollno': 90014}
print(student_info)
Output:
{'name': 'Devansh', 'age': 22, 'Rollno': 90014}
Why Is Sorting a Dictionary Necessary?
Sorting dictionaries can be helpful in various scenarios:
- The search time complexity of a list is O(n), while dictionaries offer O(1) lookup time, making them faster for key-based searches.
- Sorting helps in analyzing data efficiently when working with data structures.
- A sorted dictionary improves readability and simplifies complex operations.
Methods to Sort a Dictionary:
- Sorting by Keys
- Sorting by Values
- Using Custom Sorting Algorithms
- Reversing the Sorted Order
1. Sorting a Dictionary by Keys
Python provides built-in functions like keys() and items() to sort a dictionary based on its keys.
Example:
names = {1: 'Alice', 2: 'John', 4: 'Peter', 3: 'Andrew', 6: 'Ruffalo', 5: 'Chris'}
# Print sorted keys
print(sorted(names.keys()))
# Print sorted dictionary items
print(sorted(names.items()))
Output:
[1, 2, 3, 4, 5, 6]
[(1, 'Alice'), (2, 'John'), (3, 'Andrew'), (4, 'Peter'), (5, 'Chris'), (6, 'Ruffalo')]
Explanation:
- The dictionary keys are arranged in ascending order using the sorted() function.
- The sorted dictionary can be obtained as key-value tuples by using items().
2. Sorting a Dictionary by Values
To sort the dictionary according to values, we can combine a lambda function with the sorted() method.
Example:
dict_scores = {'Alice': 85, 'John': 92, 'Peter': 78, 'Andrew': 90}
# Sort by values
sorted_scores = dict(sorted(dict_scores.items(), key=lambda x: x[1]))
print(sorted_scores)
Output:
{'Peter': 78, 'Alice': 85, 'Andrew': 90, 'John': 92}
Explanation:
- The
sorted()function sorts based on the second element (value) of each key-value pair usinglambda x: x[1]. - The outcome is then transformed back into a dictionary.
3. Sorting a Dictionary Using Custom Algorithms
For more individualized sorting, Python lets us utilize additional arguments in the sorted() function.
Example:
daynames = {'one': 'Monday', 'six': 'Saturday', 'three': 'Wednesday', 'two': 'Tuesday', 'five': 'Friday', 'seven': 'Sunday'}
print(daynames)
number = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7}
print(sorted(daynames, key=number.__getitem__))
print([daynames[i] for i in sorted(daynames, key=number.__getitem__)])
Output:
{'one': 'Monday', 'six': 'Saturday', 'three': 'Wednesday', 'two': 'Tuesday', 'five': 'Friday', 'seven': 'Sunday'}
['one', 'two', 'three', 'five', 'six', 'seven']
['Monday', 'Tuesday', 'Wednesday', 'Friday', 'Saturday', 'Sunday']
Explanation:
- The dictionary is sorted based on a predefined numbering of days.
- We use
number.__getitem__to define the sorting order.
4. Reversing the Sorted Order
By using the reverse=True argument, we can sort dictionaries in descending order.
Example:
a = {'a': 2, 'b': 1, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
print(sorted(a.values(), reverse=True))
Output:
[6, 5, 4, 3, 2, 1]
Explanation:
reverse=Trueensures that the sorted values appear in descending order.
Download New Real Time Projects :-Click here
Complete Advance AI topics:-
Conclusion
Sorting a dictionary in Python is an essential skill when dealing with large datasets. Whether you sort by keys, values, or use custom sorting logic, Pythons built-in functions make it easy to manipulate dictionaries efficiently. By mastering dictionary sorting, you can improve the performance and readability of your Python applications.
For more Python tutorials, stay tuned to !
sort dictionary by value python
how to sort a dictionary by key in python
how to sort a dictionary in python without sort function
sort dictionary by value python descending
python sort dictionary by key=lambda
how to sort a dictionary in python alphabetically
how to sort a dictionary in python
how to sort a dictionary in python by value
how to sort a dictionary in python by value descending
how to sort a dictionary in python based on values
how to sort a dictionary in python by keys
how to sort a dictionary in alphabetical order python
lambda function in python
sorted python