Python - Maximum Value in Nested Dictionary
Last Updated :
27 Apr, 2023
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 certain ways in which this task can be performed.
Method #1 : Using loop This is brute way in which this task can be performed. In this, we iterate for each key's keys to get maximum value and set in resultant dictionary.
Python3
# Python3 code to demonstrate working of
# Maximum Value in Nested Dictionary
# Using loop
# initializing dictionary
test_dict = {'gfg' : {'a' : 15, 'b' : 14},
'is' : {'d' : 2, 'e' : 10, 'f' : 3},
'best' : {'g' : 19}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Maximum Value in Nested Dictionary
# Using loop
res = {}
for key, val in test_dict.items():
max_val = 0
for ele in val.values():
if ele > max_val:
max_val = ele
res[key] = max_val
# printing result
print("The modified dictionary : " + str(res))
Output :
The original dictionary is : {'is': {'f': 3, 'e': 10, 'd': 2}, 'gfg': {'a': 15, 'b': 14}, 'best': {'g': 19}} The modified dictionary : {'best': 19, 'is': 10, 'gfg': 15}
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
Method #2 : Using max() + dictionary comprehension This is yet another way in which this task can be performed. In this, we perform the task of extracting maximum using max() and dictionary comprehension is used to iterate and construct new dictionary.
Python3
# Python3 code to demonstrate working of
# Maximum Value in Nested Dictionary
# Using max() + dictionary comprehension
# initializing dictionary
test_dict = {'gfg' : {'a' : 15, 'b' : 14},
'is' : {'d' : 2, 'e' : 10, 'f' : 3},
'best' : {'g' : 19}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Maximum Value in Nested Dictionary
# Using max() + dictionary comprehension
res = {key: max(val.values()) for key, val in test_dict.items()}
# printing result
print("The modified dictionary : " + str(res))
Output :
The original dictionary is : {'is': {'f': 3, 'e': 10, 'd': 2}, 'gfg': {'a': 15, 'b': 14}, 'best': {'g': 19}} The modified dictionary : {'best': 19, 'is': 10, 'gfg': 15}
Method#3: Using a Recursive Generator Function
Approach
This approach involves creating a recursive generator function to yield all values in a nested dictionary. The max() function is then used to find the maximum value in the generator, and it is stored in a new dictionary with the same key as the nested dictionary in the original dictionary.
Algorithm
1. Create a recursive generator function to yield all values in a nested dictionary.
2. Use the max() function to find the maximum value in the generator.
3. Store the maximum value in a new dictionary with the same key as the nested dictionary in the original dictionary.
Python3
def flatten(d):
for k, v in d.items():
if isinstance(v, dict):
yield from flatten(v)
else:
yield v
d={'gfg' : {'a' : 15, 'b' : 14},
'is' : {'d' : 2, 'e' : 10, 'f' : 3},
'best' : {'g' : 19}}
max_dict = {}
for k, v in d.items():
max_dict[k] = max(flatten(v))
print(max_dict)
Output{'gfg': 15, 'is': 10, 'best': 19}
Time Complexity: O(n*m), where n is the number of keys in the main dictionary and m is the number of keys in each nested dictionary.
Space Complexity: O(1), as only one value is stored at a time.
Similar Reads
Python - Maximum value assignment in Nested Dictionary 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.
3 min read
Increment value in dictionary - Python In Python, dictionaries store data as keyâvalue pairs. If a key already exists, its value can be updated or incremented. This is commonly used for counting occurrences, like word frequency or item counts. Let's discuss certain ways in which this task can be performed. Using defaultdict()defaultdict
3 min read
Python - Maximum record value key in dictionary Sometimes, while working with dictionary records, we can have a problem in which we need to find the key with maximum value of a particular key of nested records in list. This can have applications in domains such as web development and Machine Learning. Lets discuss certain ways in which this task
6 min read
Python | N largest values in dictionary Many times while working with a Python dictionary, we can have a particular problem finding the N maxima of values in numerous keys. This problem is quite common while working in the web development domain. Let's discuss several ways in which this task can be performed. Method #1 : itemgetter() + it
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 - 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