How Do I Sort A Dictionary By Value In Python

Do you want to sort a Python Dictionary By Value? This article will show you how to sort a dictionary in Python by value.

Python provides several methods for sorting. You can sort the Dictionary’s values using the sort method, or you can sort it without using the sort method.

The following are the various ways to sort the dictionary by value.

Sort a Dictionary by Value In Ascending Order Using Sorted Method

The dictionary values can be sorted in ascending order. If You also want to keep the key-value pairing after sorting.

About Sorted Method In Python

  • If you have an iterable in the Python dictionary, the built-in method sorted()[1] can be quite useful for sorting iterables within the dictionary.
  • To arrange the values and keys in a specific order, use the sorted() function. This sorted function will return a new list or dictionary.

Let’s look at how to use the sorted method in Python in the code below.

Syntax

sorted(iterable, *, key=None, reverse=False)

Where,
Iterable = List of Values you want to Sort
key = If you are using Dictionary then you can specify this to store the key.
reverse = It is boolean and set to FALSE by default and hence if you want to sort in the reverse order you can change it to TRUE.
#Initializing the Dictionary with Some Values
givenDict = {'A':2, 'B':1, 'C':3, 'D':6, 'E':5}

#Using Sorted Method Sorting the Above Dictionary
#By Value
sortedDict = sorted(givenDict.items(), key=lambda dictItem: dictItem[1])

#Printing the Sorted Dictionary By Value
print(sortedDict)

Output:

[('B', 1), ('A', 2), ('C', 3), ('E', 5), ('D', 6)]

As you can see, we were able to sort the dictionary by value using the sorted method in ascending order using the code above. We used the Lambda function to return a dictionary that has been sorted by the value.

Sort Dictionary By Value in Descending Order Using Sorted Method With Lambda

You want to sort the dictionary in descending order by values. All you have to do is set the reverse argument of the sorted method to True.

In the following example code, we will see how to use reverse to get the sorted dictionary in descending order.

#Initializing the Dictionary with Some Values
givenDict = {'A':2, 'B':1, 'C':3, 'D':6, 'E':5}

#Using Sorted Method Sorting the Above Dictionary
#By Value
sortedDict = sorted(givenDict.items(), key=lambda dictItem: dictItem[1], reverse=True)

#Printing the Sorted Dictionary By Value
print(sortedDict)

Output:

[('D', 6), ('E', 5), ('C', 3), ('A', 2), ('B', 1)]

Sort Dictionary By Key Value Without Lambda

You want to sort the dictionary by value while retaining the keys, but you don’t want to use the Lamba Function.

You can do the same thing, but in this case, you will only get a list of sorted Keys, which you can then embed in a dictionary or print separately.

Let us see in the below example code.

#Initializing the Dictionary with Some Values
givenDict = {'A':2, 'B':1, 'C':3, 'D':6, 'E':5}

#Using Sorted Method Sorting the Above Dictionary
#By Value
sortedKeysByValue = sorted(givenDict, key=givenDict.get)

#Printing the Sorted Dictionary By Value
for key in sortedKeysByValue:
    print((key, givenDict[key]))

Output:

('B', 1)
('A', 2)
('C', 3)
('E', 5)
('D', 6)

Sort A Dictionary With List as Values

Assume you have a dictionary with a list of numbers as the values. And you want to sort the list based on the list value’s first appearance.

Let’s look at the example code below to see how to sort a dictionary with a list as a Value.

#Initializing the Dictionary with Some Values
givenDict = {'A':[4,8,2], 'B':[3,5,7], 'C':[1,4,9], 'D':[2,3,1], 'E':[6,9,8]}

#Using Sorted Method Sorting the Above Dictionary
#By Value
sortedListOfValues = sorted(givenDict.items(), key=lambda dictItem:dictItem[1])

#Printing the Sorted Dictionary By Value
print(sortedListOfValues)

Output:

('C', [1, 4, 9]), ('D', [2, 3, 1]), ('B', [3, 5, 7]), ('A', [4, 8, 2]), ('E', [6, 9, 8])]

The list is sorted based on its first value, as shown in the output above. That is, the first values in each list are sorted, and the dictionary is printed accordingly.

Sort Dictionary By Value Without Using Sorted Method

Do you want to sort the dictionary by value but not using the Sorted method? This can be accomplished in two ways.

The first method is to write your own sorting method and print the results, while the second is to use Python’s collections library with the Counter Method.

Let’s look at how to use the Collections Library’s Counter Method in Python in the code below.

#importing Collections Library
from collections import Counter

#Initializing the Dictionary with Some Values
givenDict = {'A':2, 'B':1, 'C':3, 'D':5, 'E':4}

#Sorting the Dictionary By Value Without Using Sort Method
sortedDict = Counter(givenDict).most_common()[::-1]

#Printing the Sorted Dictionary By Value
print(sortedDict)

Output:

[('B', 1), ('A', 2), ('C', 3), ('E', 4), ('D', 5)]

We successfully printed the sorted dictionary by value without using Python’s sorted method. Here, collections and Counter are used to sort the dictionary values and keep the keys paired.

Sort A Dictionary By Value

Wrap Up

I hope you found the solution to the above problem. I’ve discussed the various ways this problem can arise, as well as the solution.

If you still have a specific problem that has not been addressed above, please let me know in the comments section and I will gladly address it.

If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.

Further Read:

  1. Code Example: How To Add Numbers In A List Python
  2. Python – How To Delete All Files In A Directory
  3. How To Remove Non-alphanumeric Characters From String In Python
  4. How To Multiply Without Using * In Python
  5. How To Add or Append Values To a Set In Python
  6. 4 Ways To List All Subdirectories in a Directory – Python
  7. Dict To list – Convert A Dictionary to a List in Python

Leave a Comment