Python - Get items in sorted order from given dictionary

PythonServer Side ProgrammingProgramming

The Python dictionary has key and value pairs. In some situation we will need the items of the dictionary to be sorted according to the keys. In this article we'll see the different ways to get a sorted output from the items in the dictionary.

Using Operator Module

The Operator module has itemgetter function which can take 0 as the index of input parameter for the keys of the dictionary. We apply the sorted function on top of itemgetter and get the sorted output.

Example

 Live Demo

dict = {12 : 'Mon', 21 : 'Tue', 17: 'Wed'}
import operator
print("\nGiven dictionary", str(dict))
print ("sorted order from given dictionary")
for k, n in sorted(dict.items(),key = operator.itemgetter(0),reverse = False):
   print(k, " ", n)

Output

Running the above code gives us the following result −

Given dictionary {12: 'Mon', 21: 'Tue', 17: 'Wed'}
sorted order from given dictionary
12    Mon
17    Wed
21    Tue

Using the Sorted Method

The sorted method can be directly applied on a dictionary which sorts the keys of the dictionary.

Example

 Live Demo

dict = {12 : 'Mon', 21 : 'Tue', 17: 'Wed'}
#Using sorted()
print ("Given dictionary", str(dict))
print ("sorted order from given dictionary")
for k in sorted(dict):
   print (dict[k])

Output

Running the above code gives us the following result −

Given dictionary {12: 'Mon', 21: 'Tue', 17: 'Wed'}
sorted order from given dictionary
Mon
Wed
Tue

Using dict.items()

We can also apply the sorted method to dict.items. In this case both the keys and values can get printed.

Example

 Live Demo

dict = {12 : 'Mon', 21 : 'Tue', 17: 'Wed'}
#Using d.items()
print("\nGiven dictionary", str(dict))
print ("sorted order from given dictionary")
for k, i in sorted(dict.items()):
   print(k,i)

Output

Running the above code gives us the following result −

Given dictionary {12: 'Mon', 21: 'Tue', 17: 'Wed'}
sorted order from given dictionary
12 Mon
17 Wed
21 Tue
raja
Published on 18-Feb-2020 12:06:20
Advertisements