Different ways of sorting Python Dictionary by Keys


Sorting refers as the technique to arrange the elements in the defined order. There are different ways to sort the dictionary by keys in python. In this article we are going to learn those.

Using sorted() function

The sorted() function is used to sort the elements in the iterable data structures like tuple, dictionary, list etc. This function takes the iterable as the argument and returns the new sorted list containing the sorted elements as the output. Following is the syntax for using the sorted() function on dictionary.

sorted(dictionary.keys())

Where,

  • sorted is the function used to sort the dictionary by keys.

  • dictionary is the input dictionary.

  • keys is the function to get the keys of dictionary.

Example

Here in this example, we will pass the dictionary keys as the input arguments to the sorted function then the sorted elements of the dictionary will be returned as the output.

dic = {"Name" : ["Karthikeya","Anil","Srivatsav","Riyaansh","Prasad"],
      "Age":[1,30,25,1,55],
      "Skill":["python","Salesforce","Networking","python","Management"]}
print("The dictionary before sorting:",dic)
sorted_dic = sorted(dic.keys())
print("The dictionary after sorting:",sorted_dic)

Output

When we run the above code, following output will be displayed −

The dictionary before sorting: {'Name': ['Karthikeya', 'Anil', 'Srivatsav', 'Riyaansh', 'Prasad'], 'Age': [1, 30, 25, 1, 55], 'Skill': ['python', 'Salesforce', 'Networking', 'python', 'Management']}
The dictionary after sorting: ['Age', 'Name', 'Skill']

Using the “key” parameter of the sorted() function

The key parameter in the sorted() function of the python is used to specify the customized sorting order depending upon the specific attribute or property of the dictionary. Following is the syntax for using the key parameter of sorted() function to sort the dictionary by keys.

sorted(dic, key = function)

Example

In this example, we will define the key parameter of the sorted function with a function to get the specified key then the sorting will be done based on the key.

dic = [{"Name" : ["Karthikeya","Anil","Srivatsav","Riyaansh","Prasad"],
      "Age":[1,30,25,1,55],
      "Skill":["python","Salesforce","Networking","python","Management"]},
       {"Name": ["Krishna","kumari","Madhuri","Gayathri"],
        "Age" : [0,50,27,28]}]
print("The dictionary before sorting:",dic)
sorted_dic = sorted(dic, key = lambda x : x['Age'])
print("The dictionary after sorting:",sorted_dic)

Output

The output of the sorting of dictionary by key using the key parameter of sorted function.

The dictionary before sorting: [{'Name': ['Karthikeya', 'Anil', 'Srivatsav', 'Riyaansh', 'Prasad'], 'Age': [1, 30, 25, 1, 55], 'Skill': ['python', 'Salesforce', 'Networking', 'python', 'Management']}, {'Name': ['Krishna', 'kumari', 'Madhuri', 'Gayathri'], 'Age': [0, 50, 27, 28]}]
The dictionary after sorting: [{'Name': ['Krishna', 'kumari', 'Madhuri', 'Gayathri'], 'Age': [0, 50, 27, 28]}, {'Name': ['Karthikeya', 'Anil', 'Srivatsav', 'Riyaansh', 'Prasad'], 'Age': [1, 30, 25, 1, 55], 'Skill': ['python', 'Salesforce', 'Networking', 'python', 'Management']}]

Using collections.OrderedDict()

In python, there are collections module which provides an OrderedDict class used to maintain the order of insertion of the keys and this class can be used to sort the dictionary by keys. Following is the syntax of using the collections.OrderedDict().

collections.OrderedDict(sorted(dictionary.items()))

Example

Here in this example, we will the sort the dictionary by keys using the collections.OrderedDict() then output will be the sorted dictionary by keys.

import collections
dic ={"Name":["Karthikeya","Anil","Srivatsav","Riyaansh","Prasad"],
"Age":[1,30,25,1,55],
"Skill":["python","Salesforce","Networking","python","Management"]}  
print("The dictionary before sorting:",dic)
sorted_dic = collections.OrderedDict(sorted(dic.items()))
print("The dictionary after sorting:",sorted_dic)

Output

Following is the output of the sorted dictionary by keys using the collections.OrderedDict() function.

The dictionary before sorting: {'Name': ['Karthikeya', 'Anil', 'Srivatsav', 'Riyaansh', 'Prasad'], 'Age': [1, 30, 25, 1, 55], 'Skill': ['python', 'Salesforce', 'Networking', 'python', 'Management']}
The dictionary after sorting: OrderedDict([('Age', [1, 30, 25, 1, 55]), ('Name', ['Karthikeya', 'Anil', 'Srivatsav', 'Riyaansh', 'Prasad']), ('Skill', ['python', 'Salesforce', 'Networking', 'python', 'Management'])])

Using a list comprehension

The list comprehension is used to sort the dictionary by keys using the sorted() function. Following is the syntax for using the list comprehension.

key for key in sorted(dictionary.keys())

Example

In this example, we will use the list comprehension to sort the dictionary by keys. The resulting will the sorted dictionary by keys.

import collections
dic = {"Name" : ["Karthikeya","Anil","Srivatsav","Riyaansh","Prasad"],
      "Age":[1,30,25,1,55],
      "Skill":["python","Salesforce","Networking","python","Management"]}  
print("The dictionary before sorting:",dic)
sorted_keys = [key for key in sorted(dic.keys())]
print("The dictionary after sorting:",sorted_keys)
for key in sorted_keys:
    print(key,":",dic[key])	

Output

The following is the output of the sorted dictionary by keys using the list comprehension.

The dictionary before sorting: {'Name': ['Karthikeya', 'Anil', 'Srivatsav', 'Riyaansh', 'Prasad'], 'Age': [1, 30, 25, 1, 55], 'Skill': ['python', 'Salesforce', 'Networking', 'python', 'Management']}
The dictionary after sorting: ['Age', 'Name', 'Skill']
Age : [1, 30, 25, 1, 55]
Name : ['Karthikeya', 'Anil', 'Srivatsav', 'Riyaansh', 'Prasad']
Skill : ['python', 'Salesforce', 'Networking', 'python', 'Management']

Updated on: 20-Oct-2023

101 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements