Python sort a dictionary by key

Dictionary

In this post, we are going to understand with a code example in python, sort a dictionary by key ascending and descending order with code example.

Ascending order by key

Sorting Dictionary by key in ascending order

In this code example, we are sorting the dictionary by key in ascending order using the Python in-built sorted() method. It takes an iterable(tuple, list, dictionary, string) as an argument and sort its elements and return a sorted iterable object.

Syntax

sorted(iterable,key,reverse)
  • Iterable: It is a required parameter, it represents the iterable object on which we are performing sorting.
  • Key: (optional) a custom sort function to perform a sort operation.
  • Reverse : (optional) It defaults it sort an iterable in ascending order.

In this code example we are using (OneDayAverage.items()) as an iterable to sorted() method.

#Program to sort a dictionary in ascending order

OneDayAverage= {
    "Sachin": 56,
    "Dravid" : 70 ,
    "Sourav" : 80,
    "Dhoni": 90
    }

print('Sorted Dictionary:')

for item in sorted(OneDayAverage.items()):
    print(item[0] , " -" , item[1])

Output

Sorted Dictionary:

Dhoni  - 90
Dravid  - 70
Sachin  - 56
Sourav  - 80

Sort dictionary by Keys using dict.keys()

In this code example, we are sorting the dictionary by key in ascending order using the python built-in sorted(), dict.keys() method.

#code to sort a dictionary in ascending order

OneDayAverage= {
"Sachin": 56,
"Dravid" : 70 ,
"Sourav" : 80,
  "Dhoni" : 90
    }
print('Sorted Dictionary:')
for key in sorted(OneDayAverage.keys()) :
    print(key , " - " , OneDayAverage[key])

Output

Sorted Dictionary:
Dhoni  -  90
Dravid  -  70
Sachin  -  56
Sourav  -  80

sort dictionary by key using List comprehension

As we achieved above using sorted(),dict. items(),we can achieve the same using List comprehension to sort a dictionary.

##Program to sort a dictionary in ascending order

OneDayAverage= {
    "Sachin": 56,
    "Dravid" : 70 ,
    "Sourav" : 80,
    "Dhoni" : 90
    }

#sorting a dictionary using list Comprehension

print('sorted Dictionary:')

[print(key , " - " , value) for (key, value) in sorted(OneDayAverage.items()) ]


Output

Sorted Dictionary:
Dhoni  -  90
Dravid  -  70
Sachin  -  56
Sourav  -  80

Collection Module to Sort Dictionary by key

OrderedDict() method defined in the collection module, sorts the dictionary and returns a new sorted dictionary object. It is a subclass of the regular dictionary. It preserves the order of inserted key, unlike the regular dictionary.

##Program to sort a dictionary in ascending order

import collections
OneDayAverage= {
    "Sachin": 56,
    "Dravid" : 70 ,
    "Sourav" : 80,
    "Dhoni" : 90
    }

#sorting a dictionary using list collections.OrderedDict

print('Sorted Dictionary:')

order_dict =collections.OrderedDict(sorted(OneDayAverage.items()))

for key, value in order_dict.items(): 
  
  print(key,':' ,value)

Output

Sorted Dictionary:
Dhoni : 90
Dravid : 70
Sachin : 56
Sourav : 80

Sort a dictionary by key using sortedDict

SortedDict is a mutable mapping, all the keys of sortedDict are sustained in order. It is inherited from Dict class to store and sustain the order of lists of keys. We are sorting the dictionary in ascending order using sortedDict.

#Program to sort a dictionary in ascending order

from sortedcontainers import SortedDict
OneDayAverage= {
    "Sachin": 56,
    "Dravid" : 70 ,
    "Sourav" : 80,
    "Dhoni" : 90
    }

#sorting a dictionary using sortedcontainers

print('Sorted Dictionary:')

sorted_dict = SortedDict(OneDayAverage)

for key, value in sorted_dict.items():

  print(key,':',value)

Output

Sorted Dictionary:
Dhoni: 90
Dravid: 70
Sachin: 56
Sourav: 80

Sort Dictionary by key Using json.dump()

To sort the dictionary by key using json.dump() method. We pass given dictionary to json.dump() and sort_key =True.

#Program to sort a dictionary in ascending order
import json
OneDayAverage= {
    "Sachin": 56,
    "Dravid" : 70 ,
    "Sourav" : 80,
    "Dhoni" : 90 }

#sorting a dictionary using JSON Module

print('Sorted Dictionary by Key :')
sorted_Dict = json.dumps(OneDayAverage, sort_keys = True)

print(sorted_Dict)

Output

Sorted Dictionary by Key :
{"Dhoni": 90, "Dravid": 70, "Sachin": 56, "Sourav": 80}

Sort a dictionary by key Using pprint()

We pass the given dictionary to pprint() method and it prints the sorted dictionary by key

import pprint
OneDayAverage= {
    "Sachin": 56,
    "Dravid" : 70 ,
    "Sourav" : 80,
    "Dhoni" : 90 }

pprint.pprint(OneDayAverage)

Output

{'Dhoni': 90, 'Dravid': 70, 'Sachin': 56, 'Sourav': 80}

Descending order by Key

Sort dictionary by key in descending order

We are using the sorted() method to sort the dictionary in descending order by passing the reverse =True.

#Program to sort a dictionary in descending order
OneDayAverage= {
    "Sachin": 56,
    "Dravid" : 70 ,
    "Sourav" : 80,
    "Dhoni" : 90
    }

print('sorted dictionary by key in Descending order:') 

for item in sorted(OneDayAverage.items(),reverse=True):
    print(item[0] , " ::" , item[1])


Output

sorted dictionary by key in Descending order:
Sourav  :: 80
Sachin  :: 56
Dravid  :: 70
Dhoni  :: 90

Sort dictionary by key in descending order

OrderedDict() method defined in the collection module, sorts the dictionary and returns a new sorted dictionary object and we can use it sort dictionary in descending order.

#Program to sort a dictionary in descending order

from collections import OrderedDict

OneDayAverage= {
    "Sachin": 56,
    "Dravid" : 70 ,
    "Sourav" : 80,
    "Dhoni" : 90
    }

print('Sorted dictionary by key in Descending order:') 


sorted_dict = OrderedDict(sorted(OneDayAverage.items(), key=lambda t: t[0],reverse=True))

for key, value in sorted_dict.items():

 print(key,'-',value)

Output

A sorted dictionary by key in Descending order:
Sourav - 80
Sachin - 56
Dravid - 70
Dhoni - 90

Conclusion

We have understood different ways in Python to sort a dictionary by key,using this code example we can easily achieve sorting of dictionary by key.