How to Sort Dictionary by Value in Python

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.

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:

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.

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.

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.

Printing the Sorted Dictionaries

Now let’s print the sorted dictionaries to verify our results.

How to Sort Dictionary by Value in Python

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

See Also

2 thoughts on “How to Sort Dictionary by Value in Python”

Leave a Comment