Signup/Sign In
PUBLISHED ON: JULY 9, 2021

Python Program to Sort Python Dictionaries by Key or Value

In this tutorial, we will learn to sort dictionaries by key or value in Python. A dictionary can be sorted based on its keys, where the value and the keys are displayed in increasing order of the keys. There is also another way to sort a dictionary and that is based on the values where the keys and the values are displayed in increasing order of the values.

Let's see the input-output format for sorting the dictionary.

Input: {'x': 23, 'y': 60, 'z': 12}

Output: (z, 12) (x, 23) (y, 60)

Approach 1: sorting using the keys

We will be sorting the keys and the values in increasing the order of keys. We will be using the sorted() method to sort the keys. Pass the variable that will store keys in this method. It will return the keys after sorting them in ascending order.

Algorithm

Follow the algorithm to understand the approach better.

Step 1- Define a variable to store keys

Step 2- Define keys and their values

Step 3- Sort keys using the sorted() method

Step 4- Print keys in sorted order and their respective values

Python Program 1

Look at the program to understand the implementation of the above-mentioned approach.

key_value={}

key_value[5] = 10      
key_value[3] = 8
key_value[6] = 77
key_value[4] = 23
key_value[2] = 9     
key_value[1] = 43
 
print("sorting on the basis of keys")

for i in sorted(key_value) :
    print ((i, key_value[i]), end =" ")


sorting on the basis of keys
(1, 43) (2, 9) (3, 8) (4, 23) (5, 10) (6, 77)

Approach 2: sorting using the value

In this, we will sort using the value and display the keys and values in increasing order of the value. We will be using the items() method to get the keys and values from the dictionary. To sort the values, we will be using the sorted() method. To get keys of a particular value we have used a lambda function.

Algorithm

Follow the algorithm to understand the approach better.

Step 1- Define a dictionary

Step 2- Define keys and their values

Step 3- Sort values using the sorted() method

Step 4- Print the keys and their respective values

Python Program 2

Look at the program to understand the implementation of the above-mentioned approach.

key_value={}

key_value[5] = 10      
key_value[3] = 8
key_value[6] = 77
key_value[4] = 23
key_value[2] = 9     
key_value[1] = 43
 
print("sorting on the basis of values")

print(sorted(key_value.items(), key=lambda keyval: (keyval[1], keyval[0])))


sorting on the basis of values
[(3, 8), (2, 9), (5, 10), (4, 23), (1, 43), (6, 77)]

Conclusion

In this tutorial, we have seen how to sort a dictionary using keys and values. We have seen how to use the sorted() method to sort the keys or values in ascending order.



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.