How Do I Sort A Dictionary By Value In Python

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

Sorting can be performed in Python in various ways. You can sort the values of Dictionary using the sort method and you can also sort it without using the sort method. Below are the different ways you can sort the dictionary by value.

Sort a Dictionary by Value In Ascending Order Using Sorted Method

You can sort the values of the dictionary in ascending order. Also, after sorting you want to maintain the pairing of key and value.

About Sorted Method In Python

  • If you have an iterable in Python dictionary, the built-in method sorted()[1] can be quite useful for sorting iterables within the dictionary.
  • The sorted() function can be used to arrange the values and keys in a certain order. The result of this sorted function will be a new list or dictionary.

Let us see in the below example code the usage of the sorted method in Python.

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 using the above code we were able to sort the dictionary by value using the sorted method also in ascending order. Since we wanted to return a dictionary once it is sorted by the value we have used the Lambda function.

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

Now you want to sort the dictionary by values in descending order. All you are required to do is to set the reverse argument in the sorted method as True. Let us see in the below example code the usage of 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 and want to keep the keys intact as well but you do not want to use the Lamba Function. You can do that as well but in this case, you will only get the list of sorted Keys and Later you can embed it to a dictionary or print it out 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

Now suppose you have a dictionary in which the values are the list of numbers. And you want to sort the list based on the first occurrence of the list value. Let us see in the below example code and understand how to sort a dictionary with the 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])]

As you can see in the above output the list is sorted based on its first value. That is the first values of each list are sorted and the dictionary is printed based on that.

Sort Dictionary By Value Without Using Sorted Method

Do you want to sort the dictionary by value but without the using Sorted method? This can be done in two ways the first method can be you write your own sorting method and print the values or the other one is using the collections library with Counter Method in Python.

Let us see in the below example code the usage of Counter Method of Collections Library in Python.

#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 have successfully printed the sorted dictionary by value without using the sorted method in Python. Here collections and Counter are used to sort the values of the dictionary and also keep the keys paired.

How Do I Sort A Dictionary By Value In Python

Wrap Up

I hope you were able to get the answer to the above problem. I have discussed the various ways this problem can occur with the solution. If you still have any specific problem that is not discussed above then do let me know in the comment section I will be happy to 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
  8. Discord.py Bot Add Reaction To a Message Python
  9. Python Get The Minimum Value In Dictionary with Key
  10. How To Append Multiple Values To A List in Python

Leave a Reply

Your email address will not be published. Required fields are marked *