How to Sort Dictionary by Value in Python. In Python, dictionaries are widely used to store data in key-value pairs there are scenarios where you might need to sort a dictionary by its values for reporting, data analysis, or improving the readability of the output. Python provides multiple ways to sort dictionaries by value.
Table of Contents
Understanding Dictionary Sorting
Sorting a dictionary by values involves rearranging the entries so that their values are organized in a specified order, either ascending or descending.
Method to Sort a Dictionary by Values
We will explore how to sort dictionaries by their values using Python’s built-in function, focusing on clarity and effectiveness.
Prepare the Dictionary
First, let’s define a dictionary in Python that we will sort:
scores = {'Alice': 88,'Tom' : 78, 'Clara' : 67, 'Steve' : 99, 'Tony' : 63}
In this dictionary, names are keys and scores are the corresponding values.
Using the ‘sorted()’ Function
Python’s built-in 'sorted()'
function is versatile and can be used for sorting dictionaries. To sort a dictionary by value, we will use a lambda function to specify that the sorts should considered values.
Sorting in Ascending Order
Here is how to sort the dictionary in ascending order based on values.
sorted_scores = sorted(scores.items(),key = lambda x:x[1])
Explanation:
'scores.items()'
returns a view object displaying a list of the dictionary’s key-value tuple pair.'key = lambda x:x[1]'
specifies that the values (The second element in each tuple) should be used for sorting.'sorted()'
by default sorts in ascending order.
Sorting in Descending Order
To sort the dictionary in descending order, you simply add the 'reverse = True'
parameter.
sorted_scores_desc = sorted(scores.items(),key = lambda x:x[1],reverse=True)
Convert Sorted Items Back to Dictionary
The 'sorted()'
function returns a list of tuples, to convert this back into a dictionary, Use the 'dict()'
constructors.
sorted_scores_dict = dict(sorted_scores)
sorted_scores_desc_dict = dict(sorted_scores_desc)
Printing the Sorted Dictionaries
Now let’s print the sorted dictionaries to verify our results.
print("Sorted by value in ascending order: ", sorted_scores_dict)
print("Sorted by value in descending order: ", sorted_scores_desc_dict)
Sorting dictionaries by values in Python can be accomplished efficiently using the ‘sorted()’ function along with lambda expression for customization. Whether you need the data sorted in ascending or descending order, this provides a clear and concise way to organize dictionary values.
Happy Coding & Learning
2 thoughts on “How to Sort Dictionary by Value in Python”