The Wayback Machine - https://web.archive.org/web/20240118175440/https://www.geeksforgeeks.org/python-maximum-value-in-nested-dictionary/
Open In App
Related Articles

Python – Maximum Value in Nested Dictionary

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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.


Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.
Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 27 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials