Open In App

Python – Maximum record value key in dictionary

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

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 can be performed. 

Method #1: Using loop 

This is a brute-force way in which this task can be performed. In this, we iterate through each key for keys and assign to max, the maximum of a required key in the nested record.

Python3




# Python3 code to demonstrate working of
# Maximum record value key in dictionary
# Using loop
   
# initializing dictionary
test_dict = {'gfg' : {'Manjeet' : 5, 'Himani' : 10},
             'is' : {'Manjeet' : 8, 'Himani' : 9},
             'best' : {'Manjeet' : 10, 'Himani' : 15}}
   
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
   
# initializing search key
key = 'Himani'
   
# Maximum record value key in dictionary
# Using loop
res = None
res_max = 0
for sub in test_dict:
    if test_dict[sub][key] > res_max:
        res_max = test_dict[sub][key]
        res = sub
   
# printing result
print("The required key is : " + str(res))


Output

The original dictionary is : {'gfg': {'Manjeet': 5, 'Himani': 10}, 'is': {'Manjeet': 8, 'Himani': 9}, 'best': {'Manjeet': 10, 'Himani': 15}}
The required key is : best

Time complexity: O(n), where n is the number of sub-dictionaries in the main dictionary.
Auxiliary space: O(1), as we are using constant space variables to keep track of the maximum value and corresponding key.

Method #2: Using max() + lambda function 

This is a one-liner approach to solving this problem. In this, we perform the task of iteration using max key argument, passing a lambda function that binds the required logic.

Python3




# Python3 code to demonstrate working of
# Maximum record value key in dictionary
# Using max() + lambda function
   
# initializing dictionary
test_dict = {'gfg' : {'Manjeet' : 5, 'Himani' : 10},
             'is' : {'Manjeet' : 8, 'Himani' : 9},
             'best' : {'Manjeet' : 10, 'Himani' : 15}}
   
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
   
# initializing search key
key = 'Himani'
   
# Maximum record value key in dictionary
# Using max() + lambda function
res = max(test_dict, key = lambda sub: test_dict[sub][key])
   
# printing result
print("The required key is : " + str(res))


Output

The original dictionary is : {'gfg': {'Manjeet': 5, 'Himani': 10}, 'is': {'Manjeet': 8, 'Himani': 9}, 'best': {'Manjeet': 10, 'Himani': 15}}
The required key is : best

Time Complexity: O(n), where n is the number of sub-dictionaries in the main dictionary.
Auxiliary Space: O(1)

Method 3: Use the built-in function reduce from the functools module

Step-by-step approach:

  • Import the reduce function from the functools module.
  • Define a function find_max_key that takes two arguments x and y, representing two key-value pairs from the dictionary.
  • Within the function, compare the values of x and y for the given key and return the key-value pair with the maximum value.
  • Call the reduce function on the dictionary with the find_max_key function as the first argument and the test_dict.items() as the second argument.
  • Extract the key from the resulting maximum value key-value pair.
  • Print the result.

Below is the implementation of the above approach:

Python3




from functools import reduce
 
# initializing dictionary
test_dict = {'gfg': {'Manjeet': 5, 'Himani': 10},
             'is': {'Manjeet': 8, 'Himani': 9},
             'best': {'Manjeet': 10, 'Himani': 15}}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing search key
key = 'Himani'
 
# find maximum value key in dictionary using reduce
 
 
def find_max_key(x, y):
    return x if x[1][key] > y[1][key] else y
 
 
max_key = reduce(find_max_key, test_dict.items())[0]
 
# printing result
print("The required key is : " + str(max_key))


Output

The original dictionary is : {'gfg': {'Manjeet': 5, 'Himani': 10}, 'is': {'Manjeet': 8, 'Himani': 9}, 'best': {'Manjeet': 10, 'Himani': 15}}
The required key is : best

Time complexity: O(n), where n is the number of key-value pairs in the dictionary. 
Auxiliary space: O(1), as we are not using any additional data structures to store intermediate results.

Method #4: Using list comprehension and max() function

This approach uses list comprehension to extract the values of the specific key (‘Himani’ in this case) from each sub-dictionary of the main dictionary. The max() function is then used to find the maximum value among those extracted values, and the index() function is used to find the index of the sub-dictionary containing that maximum value. Finally, the keys() function is used to extract the keys of the main dictionary, and the key at the same index as the maximum value is returned.

Python3




# Python3 code to demonstrate working of
# Maximum record value key in dictionary
# Using list comprehension and max() function
 
# Initializing dictionary
test_dict = {'gfg': {'Manjeet': 5, 'Himani': 10},
             'is': {'Manjeet': 8, 'Himani': 9},
             'best': {'Manjeet': 10, 'Himani': 15}}
 
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Initializing search key
key = 'Himani'
 
# Maximum record value key in dictionary
# using list comprehension and max() function
vals = [sub[key] for sub in test_dict.values()]
 
max_val = max(vals)
idx = vals.index(max_val)
res = list(test_dict.keys())[idx]
 
# Printing result
print("The required key is : " + str(res))


Output

The original dictionary is : {'gfg': {'Manjeet': 5, 'Himani': 10}, 'is': {'Manjeet': 8, 'Himani': 9}, 'best': {'Manjeet': 10, 'Himani': 15}}
The required key is : best

Time complexity: O(n), where n is the number of sub-dictionaries in the main dictionary.
Auxiliary space: O(n), where n is the number of sub-dictionaries in the main dictionary, as a list of all values of the key ‘Himani’ is created.

Method #5: Using heapq:

Algorithm:

  1. Import the required modules.
  2. Initialize the dictionary.
  3. Initialize the search key variable.
  4. Use the max() function with the lambda function to find the key with the maximum value for the given search key.
  5. Print the result.

Python3




import heapq
 
# initializing dictionary
test_dict = {'gfg': {'Manjeet': 5, 'Himani': 10},
            'is': {'Manjeet': 8, 'Himani': 9},
            'best': {'Manjeet': 10, 'Himani': 15}}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing variables
search_key = 'Himani'
 
# using heapq module and max function to find maximum value key
max_key = max(test_dict, key=lambda k: test_dict[k][search_key])
 
# printing result
print("The required key is : " + str(max_key))
#This code is contributed by Jyothi pinjala


Output

The original dictionary is : {'gfg': {'Manjeet': 5, 'Himani': 10}, 'is': {'Manjeet': 8, 'Himani': 9}, 'best': {'Manjeet': 10, 'Himani': 15}}
The required key is : best

Time Complexity: O(n log n) where n is the number of items in the dictionary. The max() function is used to find the maximum value key, which has a time complexity of O(n log n) due to the use of a heap data structure.
Auxiliary Space: O(n) as the dictionary and the variables used have a space complexity of O(n).



Similar Reads

Python - Extract ith Key's Value of K's Maximum value dictionary
Given Dictionary List, extract i'th keys value depending upon Kth key's maximum value. Input : test_list = [{"Gfg" : 3, "is" : 9, "best" : 10}, {"Gfg" : 8, "is" : 11, "best" : 19}, {"Gfg" : 9, "is" : 16, "best" : 1}], K = "best", i = "is" Output : 11 Explanation : best is max at 19, its corresponding "is" value is 11. Input : test_list = [{"Gfg" :
9 min read
Python Program to get value of a dictionary given by index of maximum value of given key
Given a dictionary with value as a list, the task is to write a Python program that can find the maximum of any one key and output a similar index column of other key's values. Approach : Get the maximum of the given key.Get the index of the maximum element found.Check if the index of max is present in the search key, if not, return Result not Poss
8 min read
Python - Extract Key's Value, if Key Present in List and Dictionary
Given a list, dictionary, and a Key K, print the value of K from the dictionary if the key is present in both, the list and the dictionary. Input : test_list = ["Gfg", "is", "Good", "for", "Geeks"], test_dict = {"Gfg" : 5, "Best" : 6}, K = "Gfg" Output : 5 Explanation : "Gfg" is present in list and has value 5 in dictionary. Input : test_list = ["G
11 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
Python - Value Dictionary from Record List
Sometimes, while working with Python Records lists, we can have problems in which, we need to reform the dictionary taking just values of the binary dictionary. This can have applications in many domains which work with data. Let us discuss certain ways in which this task can be performed. Method #1 : Using loop + values() + update() The combinatio
6 min read
Python | Get key with maximum value in Dictionary
Given a dictionary, the task is to find the key having the maximum value. Examples : Input: {'Audi':100, 'BMW':1292, 'Jaguar': 210000, 'Hyundai' : 88} Output: Jaguar Input: {'Geeks':1900, 'for':1292, 'geek' : 88} Output: Geeks Method #1: Using max() function C/C++ Code # Python code to find key with Maximum value in Dictionary # Dictionary Initiali
3 min read
Python program to find Maximum value from dictionary whose key is present in the list
Given a list with dictionary keys and a dictionary, extract maximum from dictionary values, whose key is present in list. Examples: Input : test_dict = {"Gfg": 4, "is" : 5, "best" : 10, "for" : 11, "geeks" : 3}, test_list = ["Gfg", "best", "geeks"] Output : 10 Explanation : Max value is 11, but not present in list, 10 is of key best, which is also
6 min read
Python program to find the key of maximum value tuples in a dictionary
Given a dictionary with values as tuples, the task is to write a python program to find the key of maximum value tuples. Examples: Input : test_dict = {'gfg' : ("a", 3), 'is' : ("c", 9), 'best' : ("k", 10), 'for' : ("p", 11), 'geeks' : ('m', 2)}Output : forExplanation : 11 is maximum value of tuple and for key "for". Input : test_dict = {'gfg' : ("
6 min read
Python - Key with Maximum element at Kth index in Dictionary Value List
Given a dictionary with values as lists, the task is to write a Python program to get the key with the maximum element at the Kth index by comparing the elements of each list. Input : test_dict = {'Gfg' : [4, 6, 8, 2], 'is' : [1, 4, 5, 9], 'best' :[2, 3, 4, 10], 'for' :[4, 5, 2, 1], 'geeks' :[2, 10, 1, 8]}, K = 3 Output : best Explanation : 2, 9, 1
8 min read
Python - Maximum value in record list as tuple attribute
Many times, while dealing with containers in any language we come across lists of tuples in different forms, tuples in themselves can have sometimes more than native datatypes and can have list as their attributes. This article talks about the max of a list as a tuple attribute. Let’s discuss certain ways in which this task can be performed. Method
8 min read
Practice Tags :
three90RightbarBannerImg