How to Sort Dictionary By Key in Python

By default, Python dictionary is an unordered list of key-value pairs. Sometimes, you may need to sort the dictionary by key in Python. In this article, we will look at three different ways to sort a dictionary.


How to Sort Dictionary By Key in Python

We will look at different use cases to sort dictionary by key.


1. Display Key-Values in Sorted manner

Sometimes you may only need to display your dictionary values in ascending/alphabetical order, without actually sorting them.

Here is an example to do this.

>>> key_values={3:50,1:25,2:100,4:125}
>>> key_values
>>> {1: 25, 2: 100, 3: 50, 4: 125}
>>> for i in sorted(key_values.keys()) : 
      print(i,key_values[i])

 (1, 25)
 (2, 100)
 (3, 50)
 (4, 125)     

The keys() function returns an iterator over dictionary’s keys. Sorted() functions sorts the list of keys which we use to print dictionary key and values.

Also read : How to Install Tomcat in Ubuntu


Alternative ways to sort dictionary by key

Here is another way to sort your dictionary by keys. In the following code, sorted(key_values) returns an iterator over disctionary’s values sorted by keys.

>>> for i in sorted(key_values) : 
      print(i,key_values[i])

 (1, 25)
 (2, 100)
 (3, 50)
 (4, 125) 

Also read : How to Sort List in Python


Ordered dictionary

You can also use an ordered dictionary which automatically stores the key-value pairs in sorted order. Here is an example

 >>> key_values
 {1: 25, 2: 100, 3: 50, 4: 125}
 >>> import collections
 >>> key_values={3:50,1:25,2:100,4:125}
 >>> odict = collections.OrderedDict(sorted(key_values.items()))
 >>> odict
 OrderedDict([(1, 25), (2, 100), (3, 50), (4, 125)])

Also read : How to Install Google SDK in Ubuntu

As you can see, it is very easy to sort a dictionary in python.