Python | Sort nested dictionary by key
Last Updated :
26 Apr, 2023
Sorting has quite vivid applications and sometimes, we might come up with a problem in which we need to sort the nested dictionary by the nested key. This type of application is popular in web development as JSON format is quite popular. Let's discuss certain ways in which this can be performed.
Method #1 : Using OrderedDict() + sorted() This task can be performed using OrderedDict function which converts the dictionary to specific order as mentioned in its arguments manipulated by sorted function in it to sort by the value of key passed.
Python3
# Python3 code to demonstrate
# Sort nested dictionary by key
# using OrderedDict() + sorted()
from collections import OrderedDict
from operator import getitem
# initializing dictionary
test_dict = {'Nikhil' : { 'roll' : 24, 'marks' : 17},
'Akshat' : {'roll' : 54, 'marks' : 12},
'Akash' : { 'roll' : 12, 'marks' : 15}}
# printing original dict
print("The original dictionary : " + str(test_dict))
# using OrderedDict() + sorted()
# Sort nested dictionary by key
res = OrderedDict(sorted(test_dict.items(),
key = lambda x: getitem(x[1], 'marks')))
# print result
print("The sorted dictionary by marks is : " + str(res))
Output :
The original dictionary : {'Nikhil': {'roll': 24, 'marks': 17}, 'Akash': {'roll': 12, 'marks': 15}, 'Akshat': {'roll': 54, 'marks': 12}} The sorted dictionary by marks is : OrderedDict([('Akshat', {'roll': 54, 'marks': 12}), ('Akash', {'roll': 12, 'marks': 15}), ('Nikhil', {'roll': 24, 'marks': 17})])
Time complexity: O(n log n), where n is the number of items in the dictionary.
Auxiliary space: O(n), where n is the number of items in the dictionary
Method #2 : Using sorted() We can achieve the above result better if we just use the sorted function as it returns the result in a more usable format, dict and performs exactly the desired task.
Python3
# Python3 code to demonstrate
# Sort nested dictionary by key
# using sorted()
# initializing dictionary
test_dict = {'Nikhil' : { 'roll' : 24, 'marks' : 17},
'Akshat' : {'roll' : 54, 'marks' : 12},
'Akash' : { 'roll' : 12, 'marks' : 15}}
# printing original dict
print("The original dictionary : " + str(test_dict))
# using sorted()
# Sort nested dictionary by key
res = sorted(test_dict.items(), key = lambda x: x[1]['marks'])
# print result
print("The sorted dictionary by marks is : " + str(res))
Output :
The original dictionary : {'Nikhil': {'marks': 17, 'roll': 24}, 'Akshat': {'marks': 12, 'roll': 54}, 'Akash': {'marks': 15, 'roll': 12}} The sorted dictionary by marks is : [('Akshat', {'marks': 12, 'roll': 54}), ('Akash', {'marks': 15, 'roll': 12}), ('Nikhil', {'marks': 17, 'roll': 24})]
Time complexity: O(n log n), where n is the number of items in the dictionary.
Auxiliary space: O(n), where n is the number of items in the dictionary, due to the creation of the sorted list.
Method 3: Use the itemgetter() method from the operator module.
Step-by-step approach:
- Import the operator module
- Initialize the nested dictionary
- Print the original dictionary
- Use the sorted() function to sort the dictionary by the key
- Print the sorted dictionary
Python3
import operator
# initializing dictionary
test_dict = {'Nikhil': {'roll': 24, 'marks': 17},
'Akshat': {'roll': 54, 'marks': 12},
'Akash': {'roll': 12, 'marks': 15}}
# printing original dict
print("The original dictionary : " + str(test_dict))
# using sorted() and itemgetter()
# Sort nested dictionary by key
res = sorted(test_dict.items(), key=lambda x: (x[1]['marks'], x[0]))
# print result
print("The sorted dictionary by marks is : " + str(res))
OutputThe original dictionary : {'Nikhil': {'roll': 24, 'marks': 17}, 'Akshat': {'roll': 54, 'marks': 12}, 'Akash': {'roll': 12, 'marks': 15}}
The sorted dictionary by marks is : [('Akshat', {'roll': 54, 'marks': 12}), ('Akash', {'roll': 12, 'marks': 15}), ('Nikhil', {'roll': 24, 'marks': 17})]
Time complexity: O(n log n), where n is the number of elements in the dictionary.
Auxiliary space: O(n), where n is the number of elements in the dictionary, to store the sorted dictionary.
Similar Reads
Python - Sorted Nested Keys in Dictionary Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract all the keys of nested dictionaries and render them in sorted order. This kind of application can occur in domains in which we work with data. Lets discuss certain ways in which this task can be perf
4 min read
Sort a Nested Dictionary by Value in Python Sorting a nested dictionary in Python involves understanding its structure, defining sorting criteria, and utilizing the `sorted()` function or `.sort()` method with a custom sorting function, often a lambda. This process is essential for organizing complex, hierarchical data efficiently. Mastery of
3 min read
Python | Sort dictionary keys to list Sometimes, we wish to flatten the dictionary into list, the simple flattening is relatively easier, but when we wish to align keys and values in sorted way, i.e sorted by value, then it becomes quite a complex problem. Let's discuss certain ways in which this task can be performed. Method #1 : Using
4 min read
Python Sort Nested Dictionary by Multiple Values We are given a nested dictionary and our task is to sort a nested dictionary by multiple values in Python and print the result. In this article, we will see how to sort a nested dictionary by multiple values in Python. Example: Input : {'A': {'score': 85, 'age': 25}, 'B': {'score': 92, 'age': 30}, '
3 min read
Python - Sort Dictionary by Values and Keys Given a dictionary, sort according to descended values, if similar values, then by keys lexicographically. Input : test_dict = {"gfg" : 1, "is" : 1, "best" : 1, "for" : 1, "geeks" : 1} Output : {"best" : 1, "is" : 1, "for" : 1, "geeks" : 1, "gfg" : 1} Explanation : All values are equal, hence lexico
3 min read
Python - Sort dictionary by Tuple Key Product Given dictionary with tuple keys, sort dictionary items by tuple product of keys. Input : test_dict = {(2, 3) : 3, (6, 3) : 9, (8, 4): 10, (10, 4): 12} Output : {(2, 3) : 3, (6, 3) : 9, (8, 4): 10, (10, 4): 12} Explanation : 6 < 18 < 32 < 40, key products hence retains order. Input : test_d
5 min read
Python - Sort Dictionary key and values List Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the sorting of it, wrt keys, but also can have a variation in which we need to perform a sort on its values list as well. Let's discuss certain way in which this task can be performed. Input : test_d
6 min read
Sort a Dictionary - Python In Python, dictionaries store key-value pairs and are great for organizing data. While they werenât ordered before Python 3.7, you can still sort them easily by keys or values, in ascending or descending order. Whether youâre arranging names alphabetically or sorting scores from highest to lowest, P
5 min read
Python - Sort List by Dictionary values Sometimes while working with a Python dictionary, we can have problems in which we need to perform a sort of list according to the corresponding value in the dictionary. This can have applications in many domains, including data and web development. Let's discuss certain ways in which this task can
3 min read
Python program to sort Dictionary by Key Lengths Given Dictionary, sort by its key lengths. Input : test_dict = {"Gfg" : 4, "is" : 1, "best" : 0, "for" : 3, "geeks" : 3} Output : {'is': 1, 'Gfg': 4, 'for': 3, 'best': 0, 'geeks': 3} Explanation : 2 < 3 = 3 < 4 < 5, are sorted lengths in order. Input : test_dict = {"Gfg" : 4, "for" : 3, "ge
4 min read