Python - Maximum value assignment in Nested Dictionary
Last Updated :
27 Apr, 2023
Sometimes, while working with Python dictionaries, we can have a problem in which we need to assign to the outer key, the item with maximum value in inner keys. This kind of problem can occur in day-day programming and web development domains. Let's discuss a way in which this task can be performed.
Input : test_dict = {'Manjeet': {'English': 19, 'Maths': 1}, 'Himani': {'English': 18, 'Maths': 17}}
Output : [{'Manjeet': ('English', 19)}, {'Himani': ('English', 18)}]
Input : test_dict = {'Manjeet' : {'Maths':10}}
Output : [{'Manjeet': ('Maths', 10)}]
Method : Using Counter().most_common() + items() + loop The combination of above functions constitute the brute way to solve this problem. In this, we extract the maximum element using most_common() and items() is used to extract key-value pair.
Python3
# Python3 code to demonstrate working of
# Maximum value assignment in Nested Dictionary
# Using Counter().most_common() + items() + loop
from collections import Counter
# initializing dictionary
test_dict = {'Manjeet' : {'Maths':1, 'English':0, 'Physics':2, 'Chemistry':3},
'Akash' : {'Maths':0, 'English':0, 'Physics':3, 'Chemistry':2},
'Nikhil': {'Maths':4, 'English':2, 'Physics':2, 'Chemistry':3},
'Akshat': {'Maths':1, 'English':0, 'Physics':2, 'Chemistry':0}}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# Maximum value assignment in Nested Dictionary
# Using Counter().most_common() + items() + loop
res = []
for key, val in test_dict.items():
cnt = Counter(val)
res.append({key : cnt.most_common(1)[0]})
# printing result
print("Maximum element key : " + str(res))
OutputThe original dictionary : {'Manjeet': {'Maths': 1, 'English': 0, 'Physics': 2, 'Chemistry': 3}, 'Akash': {'Maths': 0, 'English': 0, 'Physics': 3, 'Chemistry': 2}, 'Nikhil': {'Maths': 4, 'English': 2, 'Physics': 2, 'Chemistry': 3}, 'Akshat': {'Maths': 1, 'English': 0, 'Physics': 2, 'Chemistry': 0}}
Maximum element key : [{'Manjeet': ('Chemistry', 3)}, {'Akash': ('Physics', 3)}, {'Nikhil': ('Maths', 4)}, {'Akshat': ('Physics', 2)}]
Time Complexity: O(n*n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Using the built-in max() function to find the maximum value in a nested dictionary:
Approach:
- Initialize an empty list to store the output.
- Iterate through the nested dictionary using loops.
- For each key in the outer dictionary, use the max() function to find the maximum value in the inner dictionary.
- Append a new dictionary to the output list with the key and value pair of the maximum value.
- Return the output list.
Python3
def max_value(test_dict):
output = []
for key in test_dict:
max_key, max_value = max(test_dict[key].items(), key=lambda x: x[1])
output.append({key: (max_key, max_value)})
return output
test_dict = {'Manjeet': {'English': 19, 'Maths': 1}, 'Himani': {'English': 18, 'Maths': 17}}
print(max_value(test_dict)) # Output: [{'Manjeet': ('English', 19)}, {'Himani': ('English', 18)}]
test_dict = {'Manjeet': {'Maths': 10}}
print(max_value(test_dict)) # Output: [{'Manjeet': ('Maths', 10)}]
Output[{'Manjeet': ('English', 19)}, {'Himani': ('English', 18)}]
[{'Manjeet': ('Maths', 10)}]
Time Complexity: O(n^2) where n is the number of key-value pairs in the nested dictionary. This is because we are iterating through the nested dictionary using loops and using the max() function for each inner dictionary.
Space Complexity: O(n) where n is the number of key-value pairs in the nested dictionary. This is because we are storing the output in a list.
Similar Reads
Python - Maximum Value in Nested Dictionary Sometimes, while working with python dictionary, we can have problem in which each key in itself is a record with several keys and we desire to substitute the value as maximum value of keys of dictionary. This kind of problem can have application in many domains that involves data. Lets discuss cert
4 min read
Python - Maximum available value Dictionaries Given list of dictionaries and a list, extract all the dictionaries which contain maximum available value of key from list. Input : test_list [{"Gfg" : 6, "is" : 9, "best" : 10}, {"Gfg" : 8, "is" : 11, "best" : 19}, {"Gfg" : 2, "is" : 16, "best" : 10}], K = "best", arg_list = [10, 7, 6, 12] Output :
4 min read
Python - Column Maximum in Dictionary Value Matrix Given a Dictionary with Matrix Values, compute maximum of each column of those Matrix. Input : test_dict = {"Gfg" : [[7, 6], [3, 2]], "is" : [[3, 6], [6, 10]], "best" : [[5, 8], [2, 3]]} Output : {'Gfg': [7, 6], 'is': [6, 10], 'best': [5, 8]} Explanation : 7 > 3, 6 > 2, hence ordering. Input :
5 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 - Minimum value key assignment Given two dictionaries, the task is to write a Python program to assign minimum values for matching keys from both dictionaries. Examples: Input : test_dict1 = {"gfg" : 1, "is" : 7, "best" : 8}, test_dict2 = {"gfg" : 2, "is" : 2, "best" : 10}Output : {"gfg" : 1, "is" : 2, "best" : 8}Explanation : Mi
5 min read
Python | Priority key assignment in dictionary Sometimes, while working with dictionaries, we have an application in which we need to assign a variable with a single value that would be from any of given keys, whichever occurs first in priority. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop This task can
4 min read