How to sort dictionary by value in Python?
Tags: python, tutorial, programming, beginners
Published: 2022-04-19 06:53:55

In this tutorial, we look at various methods to sort the dictionary by value in [Python](https://docs.python.org/3/). We will understand why it is required and how to do so.

## Table of Contents - Python sort dictionary by value

*   [Why do we need to sort the Python dictionary?](#why-do-we-need-to-sort-the-python-dictionary-by-value)
*   [Various methods to sort dictionary by value in Python](#various-methods-to-sort-dictionary-by-value-in-python)
*   [By converting data in the dictionary to list](#by-converting-data-in-the-dictionary-to-list)
*   [Using Bubble Sort](#using-bubble-sort)
*   [Using sorted() Method](#using-sorted-method)
*   [Using itemgetter() Method](#using-itemgetter-method)
*   [Using dict.items() and sorted() Functions](#using-dictitems-and-sorted-functions)
*   [By performing operations directly on the dictionary](#by-performing-operations-directly-on-the-dictionary)
*   [Using for Loop](#using-for-loop)
*   [Using the sorted() Function](#using-the-sorted-function)
*   [Using a Lambda Function](#using-a-lambda-function)
*   [Using dictionary.items() Method](#using-dictionaryitems-method)
*   [Closing thoughts](#closing-thoughts)

## Why do we need to sort the Python dictionary by value?

In Python, the dictionary stores unordered data that contains "key:value" pairs seperated by commas inside curly brackets. The Python dictionary class does not allow to sort to sort the items in its object. We can retrieve the values when the [key exists](https://flexiple.com/check-if-key-exists-in-dictionary-python/) and is known.

Consider a huge amount of data in a Python dictionary. In this case, to reduce the complexity of data collection by sorting the data will lead to a quick output. Thus, to save time and increase efficiency over large data, like a phonebook, we need to sort the Python dictionary.

<span id="section2"></span>

We can sort the dictionary using list and performing sorting over the list. Let us see the various ways to do this.

<span id="section3"></span>

## Various methods to sort dictionary by value in Python

### By converting data in the dictionary to list

We will first look at way to convert the data in dictionary to a list. We then perform sorting over the list to sort the Python dictionary.

#### Example-

    markdict={"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
    marklist=list(markdict.items())
    print(marklist)

#### Output-

    [('Tom', 67), ('Tina', 54), ('Akbar', 87), ('Kane', 43), ('Divya', 73)]

<span id="section4"></span>

Here, we are converting the dictionary to a list using the _list()_ function. Once the list is ready, we can perform operations over it to get desired results on the dictionary.

### Using Bubble Sort

#### Example -

    markdict={"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
    l=len(marklist)
      for i in range(l-1):
        for j in range(i+1,l):
          if marklist[i][1]>marklist[j][1]:
                t=marklist[i]
                marklist[i]=marklist[j]
                marklist[j]=t
        sortdict=dict(marklist)print(sortdict)

### Output-

    {'Kane': 43, 'Tina': 54, 'Tom': 67, 'Divya': 73, 'Akbar': 87}

<span id="section5"></span>

In this example, we use simple Bubble sort using a temporary variable _t_ and sorting the values in the list.

### Using sorted() Method

The _sorted()_ function in Python returns a sorted list from the specified iterables and returns a list of sorted items.

#### Syntax-

#### 

    sorted (iterable, key, reverse)

#### Example-

#### 

    marklist = sorted(markdict.items(), key=lambda x:x[1])
    sortdict = dict(marklist)
    print(sortdict)

#### Output-

    {'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}

<span id="section6"></span>

Here, in the _sorted()_ function, the iterable is _markdict.items_ and the key is set as _lambda x:x[1]_. After sorting the items, we create a new dictionary sortdict to call the sorted data.

### Using itemgetter() Method

In Python, the _itemgetter()_ function returns a callable object from its operand. Using the _itemgetter()_ function with the sorted() function will return sorted items in the dictionary by value.

#### Example-

    import operator

    markdict = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
    marklist= sorted(markdict.items(), key=operator.itemgetter(1)) 
    sortdict=dict(marklist)
    print(sortdict)

#### Output-

    {'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}

<span id="section7"></span>

The _operator.itemgetter(item)_ function returns a callable object that fetches item from its operand using the operand’s ___getitem__()_ method.

### Using dict.items() and sorted() Functions

The dict.items() method and the sorted() function can be used together to return the list of items sorted by values in a dictionary.

#### Example-

    markdict = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
    marklist=sorted((value, key) for (key,value) in markdict.items())
    sortdict=dict([(k,v) for v,k in marklist])
    print(sortdict)

#### Output-

    {'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}

In the above example, we sort the dictionary using _sorted()_ function and create a new dictionary sortdict with the sorted values.

<%= render "featured_jobs_section",featured_jobs: @featured_jobs, featured_jobs_skill: @featured_jobs_skill %><span id="section8"></span>

## By performing operations directly on the dictionary

<span id="section9"></span>

The Python dictionary can also be sorted without converting the items to list. Here are the ways to do it.

### Using for Loop

By using a for loop along with sorted() function in Python, we can sort the dictionary by value. Here is an example for the same.

#### Example-

    dict1 = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73} 
    sorted_values = sorted(dict1.values()) # Sort the values 
    sorted_dict = {}  

    for i in sorted_values:     
        for k in dict1.keys():         
            if dict1[k] == i:             
                sorted_dict[k] = dict1[k]             
                break
    print(sorted_dict)

#### Output-

    {'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}

<span id="section10"></span>

Here, we first use the sort() function to order the values of dictionary. The sorted() function does not re-order the dictionary in-place, hence, we store it's value in _sorted_values_. We then then loop through the sorted values, finding the keys for each value. This is finally added to the new dictionary _sorted_dict[k]_.

### Using the sorted() Function

#### Example-

    dict1 = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73} 
    sorted_dict = {} 
    sorted_keys = sorted(dict1, key=dict1.get) 
    for w in sorted_keys:     
      sorted_dict[w] = dict1[w]  
    print(sorted_dict)

#### Output-

    {'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}

<span id="section11"></span>

In this example, we use the function key on each element before comparing the values for sorting. Another function used here is _get()_ to return the values corresponding to the dictionary's key. Thus, the function _sorted(dict1, key=dict1.get)_ returns the list of keys with sorted values.

### Using a Lambda Function

We can use Python function sorted() with lambda function to sort a dictionary by value. The syntax of lambda function is as follows.

#### Syntax-

    lambda arguments: expression

#### Example-

    dict1 = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73} 
    sorted_tuples = sorted(dict1.items(), key=lambda item: item[1]) 
    sorted_dict = {k: v for k, v in sorted_tuples}  
    print(sorted_dict)

#### Output-

<span id="section12"></span>

    {'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}

### Using dictionary.items() Method

The items() method can sort the dictionary by values and return the sorted values. Below is the example of how we can use this method.

#### Example-

    from operator import itemgetter
    dictionary = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
    sort_dict= dict(sorted(dictionary.items(), key=itemgetter(1))) 
    print(sort_dict)

#### Output-

    {'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}

<span id="section13"></span>

In this example, we use the functions _sorted()_, set the iterable as dictionary.items() and the key as _key=itemgetter(1)_ to get the sorted values of the dictionary.

## Closing thoughts

We can sort the Python dictionary by values in two ways. One is by converting dictionary data to list and then sorting the list. The other way is to sort the dictionary directly.