Open In App

Python – Sort Nested keys by Value

Last Updated : 10 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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))


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 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 - Extract selective keys' values Including Nested Keys
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract selective keys' values. This problem has been solved earlier, but sometimes, we can have multiple nestings and certain keys may be present in inner records. This problem caters all the nestings for extraction of keys' values. Let's discuss certain w
7 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 efficiently sort nested dictionaries and gain a deeper unde
3 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 sorting nested dictionaries enhances data manipul
3 min read
Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Python | Add keys to nested dictionary
Addition of keys in dictionaries have been discussed many times, but sometimes, we might have a problem in which we require to alter/add keys in the nested dictionary. This type of problem is common in today's world with advent of NoSQL databases. Let's discuss certain ways in which this problem can be solved. Method #1: Using for loop Step-by-step
5 min read
Python | Safe access nested dictionary keys
Sometimes, while working with Python we can have a problem in which we need to get the 2nd degree key of dictionary i.e the nested key. This type of problem is common in case of web development, especially with the advent of NoSQL databases. Let's discuss certain ways to safely get the nested available key in dictionary. Method #1 : Using nested ge
3 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 performed. Method #1 : Using yield + isinstance() + lo
4 min read
Python - Flatten Nested Keys
Sometimes, while working with Python data, we can have a problem in which we need to perform the flattening of certain keys in nested list records. This kind of problem occurs while data preprocessing. Let us discuss certain ways in which this task can be performed. Method #1: Using loopThis is a brute-force method to perform this task. In this, we
10 min read
Python - Summation of Custom nested keys in Dictionary
Given a dictionary with keys as nested dictionaries, find the sum of values of certain custom keys inside the nested dictionary. Input : test_dict = {'Gfg' : {1 : 6, 5: 9, 9: 12}, 'is' : {1 : 9, 5: 7, 9: 2}, 'best' : {1 : 3, 5: 4, 9: 14}}, sum_key = [1] Output : 18 Explanation : 6 + 9 + 3 = 18, only values with key 1 are summed. Input : test_dict =
10 min read
Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read