Python - Sort Nested keys by Value
Last Updated :
10 May, 2023
Sometimes, while working with data records, we can have a problem in which we need to perform the sorting of nested keys of dictionary by the value of occurrence. This can have applications in arranging scores, prices etc. Lets discuss a way in which this task can be performed.
Method #1 : Using sorted() + lambda + generator expression
The combination of above methods can be used to perform this task. In this, we perform the task of sorting using sorted() and lambda and generator expression are used to bind and extracting values of dictionaries.
Python3
# Python3 code to demonstrate working of
# Sort Nested keys by Value
# Using sorted() + generator expression + lambda
# initializing dictionary
test_dict = {'Nikhil' : {'English' : 5, 'Maths' : 2, 'Science' : 14},
'Akash' : {'English' : 15, 'Maths' : 7, 'Science' : 2},
'Akshat' : {'English' : 5, 'Maths' : 50, 'Science' : 20}}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Sort Nested keys by Value
# Using sorted() + generator expression + lambda
res = {key : dict(sorted(val.items(), key = lambda ele: ele[1]))
for key, val in test_dict.items()}
# printing result
print("The sorted dictionary : " + str(res))
Output :
The original dictionary : {'Nikhil': {'English': 5, 'Maths': 2, 'Science': 14}, 'Akash': {'English': 15, 'Maths': 7, 'Science': 2}, 'Akshat': {'English': 5, 'Maths': 50, 'Science': 20}} The sorted dictionary : {'Nikhil': {'Maths': 2, 'English': 5, 'Science': 14}, 'Akash': {'Science': 2, 'Maths': 7, 'English': 15}, 'Akshat': {'English': 5, 'Science': 20, 'Maths': 50}}
Time Complexity: O(n*nlogn), where n is the length of the list test_list
Auxiliary Space: O(n), where n is the number of elements in the res list
Method #2: Using dictionary comprehension and itemgetter
- Import the "itemgetter" module from the "operator" module.
- Initialize an empty dictionary "res".
- Use a nested dictionary comprehension to iterate over the key-value pairs of "test_dict".
- For each key-value pair, sort the nested dictionary by values using the "sorted" function and passing the key and the "itemgetter" function as arguments.Create a new dictionary with the
- sorted nested dictionary and add it to the "res" dictionary.
- Return the "res" dictionary.
Python3
from operator import itemgetter
# initializing dictionary
test_dict = {'Nikhil' : {'English' : 5, 'Maths' : 2, 'Science' : 14},
'Akash' : {'English' : 15, 'Maths' : 7, 'Science' : 2},
'Akshat' : {'English' : 5, 'Maths' : 50, 'Science' : 20}}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Sort Nested keys by Value
# Using dictionary comprehension and itemgetter
res = {key : dict(sorted(val.items(), key=itemgetter(1)))
for key, val in test_dict.items()}
# printing result
print("The sorted dictionary : " + str(res))
OutputThe original dictionary : {'Nikhil': {'English': 5, 'Maths': 2, 'Science': 14}, 'Akash': {'English': 15, 'Maths': 7, 'Science': 2}, 'Akshat': {'English': 5, 'Maths': 50, 'Science': 20}}
The sorted dictionary : {'Nikhil': {'Maths': 2, 'English': 5, 'Science': 14}, 'Akash': {'Science': 2, 'Maths': 7, 'English': 15}, 'Akshat': {'English': 5, 'Science': 20, 'Maths': 50}}
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.
Similar Reads
Python | Sort JSON by value Let's see the different ways to sort the JSON data using Python. What is JSON ? JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. JSON can represent two structured types: objects and array
2 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
Sort Nested Dictionary by Value Python Descending Sorting a nested dictionary in Python based on its values is a common task, and it becomes even more versatile when you need to sort in descending order. In this article, we'll explore some different methods to achieve this using various Python functionalities. Let's dive into more ways to efficient
3 min read
Python | Sort nested dictionary by key 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. Met
4 min read
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