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.


import_contacts

You may also like:

Related Posts

  • Convert CSV to dictionary in Python
    09 May

    Convert CSV to Dictionary in Python

    Table of ContentsCSV and Dictionaries in PythonConvert CSV to Dictionary in PythonUsing the pandas.to_dict() function to convert CSV to dictionary in PythonUsing the csv module to convert CSV to dictionary in PythonUsing the filter() function to convert CSV to dictionary in PythonUsing the numpy.loadtxt() function to convert CSV to dictionary in PythonConvert CSV to List […]

  • Make requirements.txt in Python
    03 May

    Make requirements.txt in python

    Table of ContentsWhat is the requirements.txt file in Python?Ways to make requirements.txt file in PythonUsing the pip to make requirements.txt in PythonUsing the conda command to make requirements.txt file in PythonUsing the pipreqs package to make requirements.txt file in PythonConclusion What is the requirements.txt file in Python? Every package is also updated regularly and features […]

  • Create an array of 1 to 10 in Python
    03 May

    Create an Array of 1 to 10 in Python

    Table of ContentsIntroductionHow to create an array of 1 to 10 in Python?Using the range() function to create an array of 1 to 10 in Python.Using list comprehension along with the range() function to create an array of 1 to 10 in Python.Using a user-defined function to create an array of 1 to 10 in […]

  • Remove Urls from String in Python
    03 May

    Remove Urls from Text in Python

    Table of ContentsIntroductionWays to remove URLs from Text in PythonUsing the re.sub() function to remove URLs from Text in PythonUsing the re.findall() function to remove URLs from Text in PythonUsing the re.search() function to remove URLs from Text in PythonUsing the urllib.urlparse class to remove URLs from Text in PythonConclusion In this post, we will […]

  • Create a list from 1 to 100 in Python
    03 May

    Create a List from 1 to 100 in Python

    Table of ContentsWays to create a list from 1 to 100 in PythonUsing the range() function to create a list from 1 to 100 in PythonUsing the numpy.arange() function to create a list from 1 to 100 in PythonUsing the for loop with range() to create a list from 1 to 100 in PythonConclusion In […]

  • Return vs Print in Python
    16 April

    Return vs Print in Python

    Table of ContentsReturn vs Print in PythonConclusion Return vs Print in Python In Python, we work with a wide range of functions that make our code simple. We can also create functions using the def keyword. A function can be defined as per our requirement and can display something or return a value. This is […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.