Open In App

Sort Python Dictionary by Key or Value – Python

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

There are two elements in a Python dictionary-keys and values. You can sort the dictionary by keys, values, or both. In this article, we will discuss the methods of sorting dictionaries by key or value using Python.

Sorting Dictionary By Key Using sort()

In this example, we will sort the dictionary by keys and the result type will be a dictionary. 

Python
d = {'ravi': 10, 'rajnish': 9, 'sanjeev': 15}

myKeys = list(d.keys())
myKeys.sort()

# Sorted Dictionary
sd = {i: d[i] for i in myKeys}
print(sd)

Output
{'rajnish': 9, 'ravi': 10, 'sanjeev': 15}

Displaying the Keys in Sorted Order using sorted() on Keys

In this example, we are trying to sort the dictionary by keys and values in Python. Here, keys() returns an iterator over the dictionary’s keys.

Python
# Initializing key-value pairs
d = {2: 56, 1: 2, 5: 12, 4: 24}

print("Dictionary", d)

# Sorting and printing dictionary keys
for i in sorted(d.keys()):
    print(i, end=" ")

Output
Dictionary {2: 56, 1: 2, 5: 12, 4: 24}
1 2 4 5 

Sorting the dictionary by key using OrderedDict

In this example, we will sort in lexicographical order Taking the key’s type as a string.

Python
# Creates a sorted dictionary (sorted by key)
from collections import OrderedDict

d = {'ravi': '10', 'rajnish': '9', 'abc': '15'}
d1 = OrderedDict(sorted(d.items()))
print(d1)

Output
OrderedDict([('abc', '15'), ('rajnish', '9'), ('ravi', '10')])

Sorting the Keys Alphabetically Using Sorted on Dictionary

When we use sorted on a dictionary, it sorts by keys by default.

Python
# Initializing key-value pairs
d = {2: 56, 1: 2, 3: 323}

print("Dictionary", d)

# Sorting and printing key-value pairs by the key
for i in sorted(d):
    print((i, d[i]), end=" ")

Output
Dictionary {2: 56, 1: 2, 3: 323}
(1, 2) (2, 56) (3, 323) 

Sorting Alphabetically by Values using Sorted

In this example, we are trying to sort the dictionary by keys and values in Python. Here we are using to sort in lexicographical order.

Python
# Initializing the key-value pairs
d = {2: 56, 100: 2, 3: 323}

print("Dictionary", d)

# Sorting key-value pairs by value, and by key if values are the same
sorted_items = sorted(d.items(), key=lambda kv: (kv[1], kv[0]))

print(sorted_items)

Output
Dictionary {2: 56, 100: 2, 3: 323}
[(100, 2), (2, 56), (3, 323)]

Sorting Dictionary By Value using Numpy

In this example, we are trying to sort the dictionary by values in Python. Here we are using dictionary comprehension to sort our values.

Python
# Creates a sorted dictionary (sorted by key)
from collections import OrderedDict
import numpy as np

d = {'ravi': 10, 'rajnish': 9,
        'sanjeev': 15, 'yash': 2, 'suraj': 32}
print(d)

keys = list(d.keys())
values = list(d.values())
sorted_value_index = np.argsort(values)
sorted_dict = {keys[i]: values[i] for i in sorted_value_index}

print(sorted_dict)

Output
{'ravi': 10, 'rajnish': 9, 'sanjeev': 15, 'yash': 2, 'suraj': 32}
{'yash': 2, 'rajnish': 9, 'ravi': 10, 'sanjeev': 15, 'suraj': 32}


Sorting Dictionary By Value using sorted() method

In the below given example, the dictionary is sorted using a ‘lambda’ to obtain the desired result of sorting the dictionary based on values.

Python
# Key, Value of the dictionary defined
d = {'watermelon': 1, 'apple': 2, 'banana': 3}        

# Sort based on Values
val_based = {k: v for k, v in sorted(d.items(), key=lambda item: item[1])}
# item[1] represents the sorting based on value

# Sort based on reverse of Values
val_based_rev = {k: v for k, v in sorted(d.items(), key=lambda item: item[1], reverse=True)}

# Print sorted dictionary
print(val_based)
print(val_based_rev)

Output
{'watermelon': 1, 'apple': 2, 'banana': 3}
{'banana': 3, 'apple': 2, 'watermelon': 1}


Need for Sorting Dictionary in Python

We need sorting of data to reduce the complexity of the data and make queries faster and more efficient. Sorting is very important when we are dealing with a large amount of data. 

We can sort a dictionary by values using these methods:

  • First, sort the keys alphabetically using key_value.iterkeys() function.
  • Second, sort the keys alphabetically using the sorted (key_value) function & print the value corresponding to it.
  • Third, sort the values alphabetically using key_value.iteritems(), key = lambda (k, v) : (v, k))

We have covered different examples based on sorting dictionary by key or value. Reading and practicing these Python codes will help you understand sorting in Python dictionaries.

You can easily sort the values of dictionaries by their key or value.

Similar Reads:



Next Article

Similar Reads