How To Sort A Dictionary By Values In Python?

sort a dictionary by values

Sort a dictionary by values! How can we sort elements inside dictionaries using their values in Python? That is a good question while considering Dictionary in Python.

This article will discuss the various ways to sort elements kept inside dictionaries by values. However, before we proceed further, let’s discuss what a dictionary in Python is and what it means to sort a dictionary by value.

Dictionary in Python

Dictionary in Python is an important data structure. By using Dictionary, we can store data in the form of key-value pairs. Each key in a dictionary can store at most one value. While declaring a key it must be noted that the keys in the dictionary must be immutable in nature and the supported data types of declaring a key are: integers, strings, and tuples as these are immutable. Also, the dictionary has a unique property that doesn’t allow duplication of keys inside the dictionary.

Note: The older versions of Python beyond 3.7, had dictionaries with unordered data structures. But since Python 3.7 came into existence, dictionaries are ordered data structures. This implies that the elements inside the dictionaries are now stored in an ordered manner.

Creating a dictionary

You can create a dictionary in Python by enclosing key-value pairs inside curly braces ({}). Each key-value pair is separated with another key-value pair with the help of commas (,).

Syntax:

{key1 : value1, key2 : value2, key3 : value3, key4 : value4,…..}

 Let’s have a look at the below-given code snippet which describes the creation of a dictionary in Python.

 

carbon (4).png

 

Output:

carbon (3).png

 

In the source code, we can notice that each key inside a dictionary is unique and is of immutable type (here, an integer or string). We cannot declare any mutable objects (such as List) as a key. This is because we can change their content. And thus the hashing cannot be performed. Every time you change the list, you generate a new hash number. The dictionary is unable to find this newly created hash number inside itself, which generates an error.

So, do not use mutable objects as keys inside the dictionary. Instead, we can convert a list into a tuple (immutable type) and then make it a key.

Before finding out how to sort a dictionary by values, let’s have a look at a few additional functions :

items() method of a dictionary

The items() method of a dictionary is used to return a view object that displays a list of tuples containing the key-value pair of the corresponding tuple. Let’s implement a code to understand the working of this method.

carbon.png

 

In the above-written code, first of all, we have created a dictionary named rankings which contains team names as the keys and its rank as the value and later we applied the items() method over the dictionary that displays us a list of tuples containing the key-value pairs of our dictionary.

Output:

carbon (1).png

 

Lambda function/ Anonymous function in Python

The functions that are declared without a name are called anonymous functions. These anonymous functions are defined using a lambda keyword. That’s the reason why the anonymous functions are also called lambda functions.

Syntax of lambda functions is given as:

lambda arguments: expression

A lambda function can have any number of arguments. However, it has only one expression. It is evaluated and returned after the function operation. Let’s see a sample program to observe the working of the lambda functions.

carbon (2).png

 

We have created an anonymous function that calculates the square of a passed argument number and returns it to the square variable.

Output

carbon (3).png

 

sorted() function in Python

The sorted function is used to sort an iterable object in a particular order. And then it returns the result in form of a list.

Syntax

sorted(iterable, key, reverse)

The function accepts three parameters that are discussed in detail below:

  • iterable: It is an object that can be iterated. Such as a sequence type (like list, tuple, string) or a collection type (like a dictionary, set, frozen set, etc.) or it could be any other iterable object.
  • key: It is an optional parameter inside the function. It accepts a function to be passed inside it This becomes the basis over which element in the iterable is compared for sorting. The default value is set to None.
  • reverse: It is also an optional parameter and accepts Boolean values in True and False. If the value passed is True, then the sorted list will be displayed in reverse order. Otherwise, the default value is set to False, which displays the result in ascending order.

Let’s have a look at an example of using the sorted() function:

carbon (4).png

 

Here, the sorted() function takes the iterable object sorts them in ascending order by default, and returns them in the form of a list.  

The output of sorted() to sort a dictionary by values:

carbon (5).png

 

Sort a dictionary by values

Now that we have an understanding of what keys and values are inside a dictionary. Also, few additional functions such as items(), lambda functions, and sorted() function. Finally, we shall put our focus towards our main goal i.e., sorting the dictionary by its values.

To understand it in a better way, let’s formulate it in a problem statement. Recall in the earlier section, we created a dictionary representing the Test cricket rankings of different countries where the team name was the key and its ranking was the value that key holds. Our objective is to sort the team names based upon rankings (i.e., value) in ascending order. 

It should be noted that there aren’t any straightforward built-in functions that we can use for sorting the dictionary by values. Therefore, to achieve our objective we will make use of those additional Python functions that we studied earlier in the tutorial.

Make your hands dirty by coding to sort a dictionary by values

So, let’s write a Python code to create such a jumbled dictionary first, and later we will sort it and then display the sorted dictionary by value. The code can be written as:

sort a dictionary by values,

 

In the above-written code, firstly a dictionary named rankings were created. Now, to sort this rankings dictionary, we will pass it into a built-in sorted() function.

sorted() function

As discussed earlier, the sorted() method accepts three arguments, where the first argument is iterable. So, rankings.items() returns an iterable view object (its output we’ve already seen in the earlier section). The second argument is the key that accepts a lambda function. It returns the value of each key in the list. Sorting is performed over the values.

The third argument reverse = False ensures that the sorted list is obtained in ascending order. And, it is represented using the ‘sorted_ranking_list’ variable. Finally, we will convert sorted this list back into a dictionary using the dict() constructor method.

Thus, to sort a dictionary by values, we can verify our result by printing the ‘sorted_ranking’ variable our original dictionary will get sorted by the values. While saving and executing the above code, the output will look like this:

sort a dictionary by values output

 

In the output, we can notice how we managed to sort the countries by their rankings (i.e., values inside dictionaries) in ascending order as was required in our objective. Also, to sort the rankings in descending order, we can pass the reverse parameter inside the sorted function = True. It will display the sorted dictionary in descending order of rankings.

Test your understanding of different Python concepts covered in this article, attempt these practice questions now: Find question on the concept of the sort a dictionary by values here:

 

Question 1. Choose the correct output of the following code.

state = [‘New Delhi’, ‘Assam’, ‘Goa’, ‘Jammu and Kashmir’, ‘Uttar Pradesh’, ‘Rajasthan’, ‘Gujarat’  ]

print(sorted(state[ : : 2]))

  1. [ ‘New Delhi’,  ‘Goa’, ‘Uttar Pradesh’,  ‘Gujarat’  ]
  1. [ ‘Goa’, ‘Gujarat’, ‘New Delhi’,  ‘Uttar Pradesh’  ]
  1. [ ‘Assam’, ‘Goa’, ‘New Delhi ’, ‘Uttar Pradesh’]
  1. [‘Assam’, ‘Gujarat’, ‘Jammu and Kashmir’, ‘Uttar Pradesh’  ]

Correct Answer: (ii)

[ ‘Goa’, ‘Gujarat’, ‘New Delhi’,  ‘Uttar Pradesh’  ]

 The question is a combination of two concepts list slicing and then using the sorted() function. Firstly, list slicing will return a sublist in the form of [‘New Delhi’, ‘Goa’, ‘Uttar Pradesh’, ‘Gujarat’] and later it will be sorted to get the correct desired output.

 Question 2. For which of the following function it is not mandatory to have a name? 

  1. Anonymous function
  2. None of these
  3. Lambda function
  4. Both (i) and (iii)

Correct Answer: (iv) Both (i) and (iii)

Anonymous functions need not have a name. Therefore, we declare these, using the lambda keyword. Hence they are also known as the lambda function.

Question 3. Which of the following is immutable in nature? 

  1. List
  2. String
  3. Tuple
  4. Both (ii) and (iii)

Correct Answer: (iv) Both (ii) and (iii)

Both tuple and string are of an immutable type. So, once we declare them, mutating them is not possible.

Question 4. To convert a list into a dictionary we can make use of which method? 

  1. tuple()
  2. dict()
  3. listtodict()
  4. None of these

Correct Answer: (ii) dict()

We can make use of the dict() constructor method to convert a list into a dictionary.

Question 5.  Which of the following data structure in Python hold data in the form of key-value pairs in Python? 

  1. String
  2. List
  3. Dictionary
  4. Tuple

Correct Answer: (iii) Dictionary

Archana

A traveler, and explorer, Archana is an active writer at GUVI. You can usually find her with a book/kindle binge-reading (with an affinity to the mystery/humor).

You may also like...

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x