How to Sort Dictionary by Value in Python

Spread the love

We can sort the dictionary by value using a sorted() function in Python. It can be used to sort a dictionary by value in ascending order or descending order. This function sorts iterable objects like lists, tuples, sets, and dictionaries. In this article, I will explain how to sort a dictionary by value in ascending/descending order using Pyhton sorted() function.

1. Quick Examples of Sort Dictionary by Value in Python

Following are quick examples of sorting dictionaries by value.


# Below are the quick examples

# Example 1:  Sort the dictionary by value in ascending order
sorted_list = sorted(my_dict.items(), key = lambda x:x[1])

# Example 2:  Sort the dictionary by value in descending order 
sorted_list = sorted(my_dict.items(), key = lambda x:x[1], reverse = True)

# Example 3: Update the existing dictionary with sorted values
sorted_list = sorted(my_dict.items(), key = lambda x:x[1]
my_dict.clear()
for key, value in sorted_list:
    my_dict[key] = value

# Example 4: Sort the dictionary values
print(sorted(my_dict.values()))

2. What is Python Dictionary

A Python dictionary is a collection that is unordered, mutable, and does not allow duplicates. Each element in the dictionary is in the form of key:value pairs. Dictionary elements should be enclosed with {} and key: value pair separated by commas. The dictionaries are indexed by keys.

Let’s create a Python dictionary where, the 'keys' are 'string' type and 'values' are 'int' type.


# Create dictionary
my_dict = {'Apple':5, 'papaya':6, 'kiwi':4, 'pomegranate':11, 'strawberry':10}
print(my_dict)
print(type(my_dict))

Yields below output.

python Sort Dictionary Value
Python Dictionary

3. Sort Python Dictionary by Value in Ascending Order

Using the sorted() method we can sort the dictionary by value in Python. Pass the items() function as an iterable and key param(specify to sort by values using lambda function) into this function, it will sort the dictionary by values and finally, get the sorted dictionary by values using the dict() function.


# Sort the dictionary by value in ascending order
sorted_list = sorted(my_dict.items(), key = lambda x:x[1])
print(sorted_list)

Yields below output.

Sort Dictionary by Value in Python
Dictionary Sorted by Key

4. Sort Dictionary by Value in Descending Order

To sort the Python dictionary by value in descending order use the ‘reverse‘ param as ‘True‘ and then pass it into the sorted() function.


# Sort the dictionary by value in descending order 
sorted_list = sorted(my_dict.items(), key = lambda x:x[1], reverse = True)
print(sorted_list)

# Output:
# [('pomegranate', 11), ('strawberry', 10), ('papaya', 6), ('Apple', 5), ('kiwi', 4)]

5. Update the Existing Dictionary with Sorted Values in Python

When we sort the dictionary by using the sorted() function it will return a list of tuple values, to update the original dictionary with a sorted key-value pair we can use the dict.items() function. Using this we can get a list of values and sort them, and then use a for loop to update the dictionary with sorted key-value pair.


# Update the existing dictionary with sorted values
sorted_list = sorted(my_dict.items(), key = lambda x:x[1]
my_dict.clear()
for key, value in sorted_list:
    my_dict[key] = value
print(my_dict)

# Output:
# {'kiwi': 4, 'Apple': 5, 'papaya': 6, 'strawberry': 10, 'pomegranate': 11}

6. Get Only Values After Sorting by Value

Let’s pass dict.values() function into sorted() function, it will return a list of all sorted values stored in the dictionary. For example,


# Sort the dictionary values
print(sorted(my_dict.values()))

# Output:
# [4, 5, 6, 10, 11]

7. Conclusion

In this article, I have explained how to sort a dictionary by value in ascending/descending order using Pyhton sorted() function. And also explained how we can update the existing dictionary with sorted key-value pairs.

Related Articles

References

Vijetha

With 5 of experience in technical writing, I have had the privilege to work with a diverse range of technologies like Python, Pandas, NumPy and R. During this time, I have consistently demonstrated my ability to grasp intricate technical details and transform them into comprehensible materials.

Leave a Reply

You are currently viewing How to Sort Dictionary by Value in Python