Sort A Dictionary By Key In Python

In this tutorial, we will be going over 3 ways to sort a dictionary by key in python. Dictionary is a very useful data structure in python. But, it is unordered. Sometimes we might wanna order the unordered. In the following tutorial, we will be looking at how to sort a dictionary by key and displaying the key:value pair.

Dictionary

Dictionary holds key:value pair. Keys are unique and are used to map to its respective values. We will be sorting the keys and then printing the respective values later.

Get to know: List and dictionary comprehension in python

Sort a Dictionary by Key in Python in 3 different ways

We will be using dictionary.sorted() function to sort the keys in the dictionary. Then there are two different ways to iterate over the keys in the dictionary. This iteration process is needed to print the key value pair in the sorted order.

Let’s assume the inputted dictionary is:

dictionary = {	
  'LeBron':23,
  'Kobe':24,
  'Curry':30,
  'Durant':35		
  }

Method #1: dict.keys()

dictionary.key()

It returns an iterable view of all the keys in dictionary.

for key in sorted(dictionary.keys()):
    print(key , ":" , dictionary[key])

Here, we are sorting the keys in the dictionary first using sorted(dictionary.key()). Then we take each key from this sorted list and print it with its corresponding value, i.e. key value pair.

Method #2: dict.items()

dictionary.items()

It returns an iterable sequence of tuples that contains all key value pairs in dictionary. Hence, now the key value pair is grouped together and pair[0] is key and pair[1] is the respective value.

for pair in sorted(dictionary.items()):
    print( pair[0] , " :" , pair[1] )

Here, we are sorting the tuples in the dictionary first using sorted(dictionary.items()). Then we print the key value pair using pair[0] and pair[1].

Method #3: Using String Literals

for key in sorted(dictionary):
    print("%s: %s" % (key, dictionary[key]))

Here, we are sorting the keys in the dictionary first using sorted(dictionary). Then we take each key from this sorted list and print it with its corresponding value, i.e. key value pair. But, here the output is a string literal. We are also using print() function properties to print the key value pair. You can read more about it here.

So here it is, 3 ways to sort a dictionary by key in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *