How to Sort Dictionary by Value & Key in Python [6 Different Ways]

In this  Python tutorial, we will understand the implementation of Python Dictionary Sort. Here we will learn how to sort a particular Python Dictionary either by using a key or by using a value.

In Python, we can sort a dictionary either by key or by value using the sorted() function. However, for both key and value, there are multiple ways to sort Python Dictionary.

  • Python dictionary sort using sorted()
  • Python dictionary sort by key
    • Using sorted() Method 
    • Using for loop
    • Using items() Method
  • Python dictionary sort by value
    • Using for Loop
    • Using lambda Function
    • Using dictionary.items() Method

But before we jump to the examples, we need to understand the need of sorting the Python Dictionary.

A Python Dictionary is a collection of key-value pairs that allow for efficient access and retrieval of values based on their corresponding keys.

Dictionaries in Python are unordered, and mutable, and can store any type of data as values, including other dictionaries. However, there are reasons due to why we might need to sort the dictionary.

As a result, sorting a dictionary in Python can provide several benefits, including improved readability, processing efficiency, presentation, algorithmic needs, and consistency.

Python dictionary sort using sorted()

The sorted() function in Python helps to sort the elements of a sequence (such as a list, tuple, or string) in a specific order (either ascending or descending). It returns a new sorted list object and does not modify the original sequence.

Here is the Syntax of the sorted() function.

sorted
      (
       iterable,
       Key=None,
       reverse=False
      )
  • It consists of a few parameters
    • iterable: This function can be used on all iterables in ascending order.
    • Key: If you want to modify the sorting process then you can use this key function by default its value will be none.
    • reverse: Here you can see reverse=False. It is for ascending order and if you want numbers in descending order then you can set this reverse flag order as true

Note: If you decide that you are not using the optional parameter key and reverse. Python will automatically sort the items in ascending order.

Now, let us look at an example where we will sort the dictionary by key and value using the sorted() function.

# Defining a dictionary
Countries = {
    6:'Canada',
    2:'United Kingdom',
    1:'United States',
    9:'Australia',
    7:'China'
}  
 
# Sorting by keys    
sorted_countries_by_keys = sorted(Countries.keys())
print("Sorted Keys:", sorted_countries_by_keys)  

# Sorting by values
sorted_countries_by_values = sorted(Countries.values())
print("Sorted Values:",sorted_countries_by_values)  

In the above example, we used the sorted() function to first the keys of the dictionary. And after this, we used the same function to the values of the dictionary in ascending order.

READ:  Adding Variables in Python

Here is the end result of the above Python program.

Python Dictionary sort
Sorting Python DIctionary using sorted()

Read: Python Concatenate Dictionary

Python dictionary sort by key

In this section, we will understand various methods that we can use to sort Python Dictionary by key.

Method-1: Using for loop

One way to sort a Python dictionary by keys is by using the for loop. Here we will use the sorted() function to sort the keys of the dictionary in ascending order.

And then we use the for loop to iterate over sorted keys and create a new sorted dictionary.

# Defining a dictionary
Countries = {
    6:'Canada',
    2:'United Kingdom',
    1:'United States',
    9:'Australia',
    7:'China'
}  

# Actual Dictionary
print("Original Dictionary:", Countries)


# Sorting dictionary by values
print("Sorted Dictionary:")
sorted_dictionary = {}
for i in sorted(Countries.keys()):
        sorted_dictionary[i] = Countries[i]
        
print(sorted_dictionary)

Once we execute the above Python program, we will get the sorted dictionary by keys.

Python Dictionary sort by keys
Sorting Python Dictionary by keys using for loop

Read: How to delete a Dictionary in Python

Method 2: Using dictionary.items()

Here, we use the dictionary.items() method to get an object of all key-value pairs from a dictionary as a tuple. And then we will use the sorted() function of the tuple values.

This will result in sorting the dictionary by keys. Here is a sample code for this execution.

# Defining a dictionary
Countries = {
    6:'Canada',
    2:'United Kingdom',
    1:'United States',
    9:'Australia',
    7:'China'
} 

print("Orignal Dictionary:", Countries)

sorted_dict = sorted(Countries.items())
# Sorted Dictionary
print("Sorted Dictionary:", sorted_dict)

The result of the above Python program is shown below.

Python Dictionary sort by keys using items
Sorting Python Dictionary by keys using dict.items()

At the end of this section, we will understand how to sort Python Dictionary by keys using for loop & dictionary.items() methods.

Read: Python dictionary pop

Python dictionary sort by value

In this section, we will understand various methods that we can use to sort Python dictionaries by value.

READ:  How to Escape Sequence in Python

Method-1: Using dictionary.items() & lambda

One way to sort the Python dictionary by values is by using the combination of dictionary.items() and lambda function

# Defining a dictionary
Countries = {
    6:'Canada',
    2:'United Kingdom',
    1:'United States',
    9:'Australia',
    7:'China'
}  

# Actual Dictionary
print("Original Dictionary:", Countries)

# Sorting dictionary by values
sort_dictionary= dict(sorted(Countries.items(), key=lambda item: item[1])) 
print("Sorted Dictionary by value: ", sort_dictionary)

Here we are sorting the Countries dictionary and creating a new sorted dictionary named sort_dictionary.

Original Dictionary: {6: 'Canada', 2: 'United Kingdom', 1: 'United States', 9: 'Australia', 7: 'China'}
Sorted Dictionary by value:  {9: 'Australia', 6: 'Canada', 7: 'China', 2: 'United Kingdom', 1: 'United States'}

Method-2: Using dictionary.items() & itemgetter

Here we will understand the use of dictionary.items() and itemgetter function in Python.

The dictionary.items() will help to the key-value pair as a tuple while itemgetter function will give an object containing each item in iterable.

Here is an example of the above approach in Python.

# Importing itemgetter
from operator import itemgetter

# Defining a dictionary
Countries = {
    6:'Canada',
    2:'United Kingdom',
    1:'United States',
    9:'Australia',
    7:'China'
}  

# Actual Dictionary
print("Original Dictionary:", Countries)

# Sorting dictionary by values
sort_dict= dict(sorted(Countries.items(), key=itemgetter(1))) 
print("Sorted Dictionary by value: ", sort_dict)

The result of the above Python program is given below.

Original Dictionary: {6: 'Canada', 2: 'United Kingdom', 1: 'United States', 9: 'Australia', 7: 'China'}
Sorted Dictionary by value:  {9: 'Australia', 6: 'Canada', 7: 'China', 2: 'United Kingdom', 1: 'United States'}

Method-3: Using numpy module

While, np.argsort() is a function in the Python numpy library, which returns the indices that would sort an array.

Here in this method, we will discuss how to sort Python Dictionary by value using np.argsort(). Here is an example of using the np.argsort() in Python

from collections import OrderedDict
import numpy as np

# Defining a dictionary
Countries = {
    'Canada': 23,
    'United Kingdom': 12,
    'United States': 27,
    'Australia': 11,
    'China': 7
}  

# Actual Dictionary
print("Original Dictionary:", Countries)


# Sorting dictionary by values
keys = list(Countries.keys())
values = list(Countries.values())
sorted_value_index = np.argsort(values)
sorted_dict = {keys[i]: values[i] for i in sorted_value_index}
 
print("Sorted Dictionary: ",sorted_dict)

The final result of the above Python program is given below.

Original Dictionary: {'Canada': 23, 'United Kingdom': 12, 'United States': 27, 'Australia': 11, 'China': 7}
Sorted Dictionary:  {'China': 7, 'Australia': 11, 'United Kingdom': 12, 'Canada': 23, 'United States': 27}

So, at the end of this section, we have seen how to sort Python Dictionary by values using the dictionary.items(), lambda, and numpy module.

READ:  Fibonacci series in Python [Complete program with 13 different examples]

You may also like to read the following python tutorials.

Conclusion

So, in this Python tutorial, we understood how to sort the Dictionary in Python by key and value. And for this, we have covered different methods with various examples.

  • Python dictionary sort using sorted()
  • Python dictionary sort by key using For Loop
  • Python dictionary sort by key using items() Method
  • Python dictionary sort by value
  • Python dictionary sort by value using for Loop
  • Python dictionary sort by value using lambda Function
  • Python dictionary sort by value using dictionary.items() Method