Sort dictionary by value in python

Sort dictionary by value in Python

The elements of the given data might sometimes need sorting to make it easier to read, visualize and understand. This tutorial focuses on the different ways available to sort dictionary by value in Python.

What is a dictionary in Python?

Dictionaries are one of the four in-built data types that Python provides for the storage of data. It is utilized to store the elements in a variable in key:value pairs. It does not allow duplicates and is ordered. Dictionaries were initially unordered until the release of Python 3.7.

Why is there a need to sort a dictionary?

The elements in a dictionary, as mentioned above, are stored in key:value pairs. It is therefore very important to sort the data in a manner so that it is aesthetic and visually easy to understand.

How to sort sort dictionary by value in Python?

Using for loop along with the sorted() function.

This can be simply implemented by using a for loop along with the sorted() function. The sorted() function is an in-built function that simply provides the sorted list of the given iterable, which in this case, is a dictionary.

The following code uses the for loop along with the sorted() function.

The above code provides the following output:

{1: 5, 3: 8, 2: 10}
Explanation:
  • A dictionary dictx is declared and it’s key:value pairs are defined.
  • The sorted() function is utilized on the given dictionary to order all the values of it.
  • Then, the for loop is utilized to find keys for each of the values present by iterating over the sorted values.
  • The key:value pairs that are found are then represented in the sorted order through a fresh dictionary.

We should note that by using the sorted() function on the dictionary, we cannot change the order of a dictionary. We simply use a fresh dictionary to show the sorted elements.

Using the sorted() function to sort dictionary by value in Python.

In the above method, we used the sorted() function along with the for loop. In this method, we will make use of a parameter that the sorted() function takes in to sort dictionary by value in Python.

The sorted function is written as sorted(dictx, key=dictx.get). Here, the key parameter is a method that comes into play every time the values need to be compared for sorting. The get() method simply gets the values for the key of the dictionary.

The following code uses the sorted() function to sort sort dictionary by value in Python.

The above code provides the following output:

{1: 5, 3: 8, 2: 10}

The advantage that this method holds over the above-mentioned method is that the length of the code of the former is way less than that of the latter.

Using operator.itemgetter() function to sort sort dictionary by value in Python.

The itemgetter() function can be imported from the operator module in Python. This function is utilized to simply provide the callable object that returns an item from a given object.

The following code uses the operator.itemgetter() function to sort sort dictionary by value in Python.

The above code provides the following output:

{1: 5, 3: 8, 2: 10}
Explanation:
  • A dictionary dictx is declared and it’s key:value pairs are defined.
  • The dictionary is then sorted, and converted to a tuple with the help of the sorted() function and the operator.itemgetter() function.
  • The sorted tuple is then finally converted to a new dictionary and its values are displayed as the output.

Using lambda function to sort sort dictionary by value in Python.

Lambda functions can be simply defined as an unnamed or anonymous function, which has only a single expression but can have a countless number of arguments.

A lambda function can be utilized as an alternative to the operator.itemgetter() function and does not need us to import the operator module to the code.

The following code uses the lambda function to sort sort dictionary by value in Python.

The above code provides the following output:

{1: 5, 3: 8, 2: 10}
Explanation:
  • A dictionary dictx is declared and it’s key:value pairs are defined.
  • The dictionary is then sorted, and converted to a tuple with the help of the sorted() function and a lambda function.
  • The sorted tuple is then finally converted to a new dictionary and its values are displayed as the output.

Using the OrderedDict() method to sort sort dictionary by value in Python.

The code can be further shortened by making use of the OrderedDict() function. This function is a part of the collections library, which needs to be imported to the python code for this method to work.

The following code uses the OrderedDict() method to sort sort dictionary by value in Python.

The above code provides the following output:

OrderedDict([(1, 5), (3, 8), (2, 10)])

We should note that although it lessens the length of the code, this function displays the output as a dictionary-compatible type instead of an actual dictionary.

That’s all about how to sort dictionary in Python.

Related Posts

  • Python check for null
    17 November

    How to check for null in Python

    Table of ContentsHow to check if a variable is NULL in Python?Using the is operator to check if a variable is NULL in Python.Using the if condition to check if a variable is NULL in Python.Using the not equal to operator to check if a variable is NULL in Python. This article demonstrates the different […]

  • Get class name in Python
    17 November

    Get class name in Python

    Table of ContentsHow to get the attributes of an object?Get Class name in python using the __class__ attribute Get Class name in python using type() functionConclusion While working with objects in python, several times we need to get their class name. In this article, we will discuss several ways to get the class name of an […]

  • Python print to file
    17 November

    How to Print to File in Python?

    Table of ContentsThe print() function in pythonHow to Print to file in python?Print to file using the file parameter in the print functionPrint to file by redirecting standard outputConclusion We use the print() function in python to print any text to standard output. In this article, we will see how we can use the print() […]

  • Python absolute path
    17 November

    Get Absolute Path in Python

    Table of ContentsWhat is an absolute path to a file? How to get absolute path in PythonUse abspath to get the absolute path to file use pathlib module to get the absolute path to file Conclusion We often use files to store the outputs of our programs in permanent storage. Generally, we work with relative […]

  • Python sort list of lists
    17 November

    Sort List of Lists in Python

    Table of ContentsSort List of Lists Using the sort() Method in PythonUsing the itemgetter() methodUsing Lambda FunctionsSort List of Lists Using the sorted() Function in PythonSort lists of lists on the basis of the length of the inner listsConclusion Several times we use 2-D lists or lists of lists in our programs to represent a […]

  • Python print type of variable
    16 November

    Print type of variable in Python

    Table of ContentsWhat is the type of variable in Python?Ways to print type of variable in PythonUsing the type() functionUsing the isinstance() functionUsing the __class__() functionConclusion What is the type of variable in Python? We use variables to store data in a reserved memory location. The type of a variable defines the memory allocated to […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.