Sort Dictionary by Value in Python (Multiple Approaches)

Python | sorting a dictionary by value: In this tutorial, we will learn how to sort a dictionary by value using the multiple approaches. Submitted by Sapna Deraje Radhakrishna Last updated : June 11, 2023

The Python dictionary is not a sorted collection. The reason for it being not sorted helps in the speed of access. Whenever, you need to sort a dictionary by value - we need to use some of the methods and other techniques to achieve this task.

To sort a Python dictionary, there can be multiple approaches. Here, we are discussing some of them. They are:

  1. Using the sorted() function and operator module
  2. Using the sorted() function and lambda expression
  3. Using the sorted() function and list comprehension
  4. Using the sorted() function and OrderedDict along with lambda function

Approach 1: Using the sorted() function and operator module

Here, we will use the sorted() method by passing the dictionary data and key as operator.itemgetter(1). Where, operator.itemgetter(1) returns a callable object that fetches an item from its operand.

# Importing operator module
import operator

# Create a dictionary
data = {"a": 1, "c": 3, "b": 5, "d": 4}

# Print original dictionary
print("Original dictionary:")
print(data)

# Sort dictionary by value
result = sorted(data.items(), key=operator.itemgetter(1))

# Print sorted dictionary
print("Sorted dictionary:")
print(result)

Output

Original dictionary:
{'a': 1, 'c': 3, 'b': 5, 'd': 4}
Sorted dictionary:
[('a', 1), ('c', 3), ('d', 4), ('b', 5)]

In the above example, we have used the operator module to sort the items in the dictionary by value. The output of the above function is of type list which is a list of tuples sorted by the second element in each tuple. Each tuple contains the key and value for each item found in the dictionary.

Approach 2: Using the sorted() function and lambda expression

Here, we will use the sorted() method by passing the dictionary data and key as key = lambda i:i[1]. It will return a sorted dictionary.

# Importing operator module
import operator

# Create a dictionary
data = {"a": 1, "c": 3, "b": 5, "d": 4}

# Print original dictionary
print("Original dictionary:")
print(data)

# Sort dictionary by value
result = sorted(data.items(), key = lambda i:i[1])

# Print sorted dictionary
print("Sorted dictionary:")
print(result)

Output

Original dictionary:
{'a': 1, 'c': 3, 'b': 5, 'd': 4}
Sorted dictionary:
[('a', 1), ('c', 3), ('d', 4), ('b', 5)]

Approach 3: Using the sorted() function and list comprehension

Here, we will use the sorted() method by passing the list comprehension. Where list comprehension is a shorter syntax to create a new list based on the values of an existing list.

# Importing operator module
import operator

# Create a dictionary
data = {"a": 1, "c": 3, "b": 5, "d": 4}

# Print original dictionary
print("Original dictionary:")
print(data)

# Sort dictionary by value
result = sorted((value, key) for (key,value) in data.items())

# Print sorted dictionary
print("Sorted dictionary:")
print(result)

Output

Original dictionary:
{'a': 1, 'c': 3, 'b': 5, 'd': 4}
Sorted dictionary:
[(1, 'a'), (3, 'c'), (4, 'd'), (5, 'b')]

Approach 4: Using the sorted() function and OrderedDict along with lambda function

Here, we will use the sorted() method by passing the dictionary data and lambda expression. And, then we will use OrderedDict() to get the sorted dictionary by value.

# Importing operator and OrderedDict
import operator
from collections import OrderedDict

# Create a dictionary
data = {"a": 1, "c": 3, "b": 5, "d": 4}

# Print original dictionary
print("Original dictionary:")
print(data)

# Sort dictionary by value
result = OrderedDict(sorted(data.items(), key=lambda i: i[1]))

# Print sorted dictionary
print("Sorted dictionary:")
print(result)

Output

Original dictionary:
{'a': 1, 'c': 3, 'b': 5, 'd': 4}
Sorted dictionary:
OrderedDict([('a', 1), ('c', 3), ('d', 4), ('b', 5)])

In the above example the output if of type dictionary.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.