/  Technology   /  Sorting a Dictionary in Python
sorting dictionary in python

Sorting a Dictionary in Python

Dictionary is a collection of items where each item contains a key value pair.

In this article we will discuss below sorting operations on dictionary.

  1. Sorting by keys
  2. Sorting by values
  3. Custom sorting algorithms – string, number
  4. Reversing the sorted order

Let’s discuss them with an example.

 

1. Sorting by keys

 

Example:

 

#dictionary a
a = {1:2 ,2:1 ,4:3 ,3:4 ,6:5 ,5:6 }
#printing a sorted list of the keys
print(sorted(a.keys()))
#printing the sorted list with items.
print(sorted(a.items()))

 

Output:

 

Sorting a Dictionary in Python

 

2. Sorting By Values

 

We can also use the values as well for sorting.

 

Example:

 

x = {'A':2 ,'B':1 ,'C':3 ,'D':4 ,'E':5 ,'F':6 }
print(sorted(x.values() ))

 

Output:

 

Sorting a Dictionary in Python

3. Custom Sorting Algorithm – String , Number

 

By using other arguments in the sorted method, we can also perform complex sorts

 

Example:

 

day = { 'one' : 'Mon' , 'two' : 'Tue' , 'three' : 'Wed' , 'four' : 'Thu' , 'five': 'Fri' , 'six' : 'Sat' , 'seven': 'Sun'}
print(day)
number = { 'one' : 'A' , 'two' : 'B' , 'three' : 'C' , 'four' : 'D' , 'five' : 'E' , 'six' : 'F' , 'seven' : 'G'}
print(sorted(day , key=number.__getitem__))
print([day[i] for i in sorted(day , key=number.__getitem__)])

 

Output:

 

Sorting a Dictionary in Python

 

4. Reversing The Sorted Order

 

Below example shows how to reverse the order of the sorted dictionary.

 

Example:

 

x = {'A':2 ,'B':1 ,'C':3 ,'D':4 ,'E':5 ,'F':6 }
print(sorted(x.values() ,  reverse= True))

 

Output:

 

Sorting a Dictionary in Python

 

It is much easier to work on dictionaries as they are mutable and have a search time complexity less than that of a list.

Leave a comment