Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Minimum Value Keys in Dictionary - Python
Next article icon

Python – Maximum record value key in dictionary

Last Updated : 14 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
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).



Next Article
Minimum Value Keys in Dictionary - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python dictionary-programs
Practice Tags :
  • python

Similar Reads

  • Minimum Value Keys in Dictionary - Python
    We are given a dictionary and need to find all the keys that have the minimum value among all key-value pairs. The goal is to identify the smallest value in the dictionary and then collect every key that matches it. For example, in {'a': 3, 'b': 1, 'c': 2, 'd': 1}, the minimum value is 1, so the res
    4 min read
  • 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
  • Add a key value pair to Dictionary in Python
    The task of adding a key-value pair to a dictionary in Python involves inserting new pairs or updating existing ones. This operation allows us to expand the dictionary by adding new entries or modify the value of an existing key. For example, starting with dictionary d = {'key1': 'geeks', 'key2': 'f
    3 min read
  • Python program to find second maximum value in Dictionary
    Dictionaries in Python is same as Associative arrays or Maps in other languages. Unlike lists, dictionaries stores data in key-value pair.Let's see how to find the second maximum value in a Python dictionary.Method #1: Naive Approach: A general approach is to find the largest value of the dictionary
    3 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
    6 min read
  • Python - Extract Maximum Keys' value dictionaries
    Given a dictionary, extract all the dictionary which contains a any key which has maximum values among other keys in dictionary list. Input : [{"Gfg" : 3, "is" : 7, "Best" : 8}, {"Gfg" : 9, "is" : 2, "Best" : 9}, {"Gfg" : 5, "is" : 4, "Best" : 10}, {"Gfg" : 3, "is" : 6, "Best" : 14}] Output : [{"Gfg
    6 min read
  • Dictionary items in value range in Python
    In this article, we will explore different methods to extract dictionary items within a specific value range. The simplest approach involves using a loop. Using LoopThe idea is to iterate through dictionary using loop (for loop) and check each value against the given range and storing matching items
    2 min read
  • Python - Unique Values of Key in Dictionary
    We are given a list of dictionaries and our task is to extract all the unique values associated with a given key. For example, consider: data = [ {"name": "Aryan", "age": 25}, {"name": "Harsh", "age": 30}, {"name": "Kunal", "age": 22}, {"name": "Aryan", "age": 27}]key = "name" Then, the unique value
    4 min read
  • Python | Selective key values in dictionary
    Sometimes while working with Python dictionaries, we might have a problem in which we require to just get the selective key values from the dictionary. This problem can occur in web development domain. Let's discuss certain ways in which this problem can be solved. Method #1: Using list comprehensio
    7 min read
  • Python | Least Value test in Dictionary
    While working with dictionary, we might come to a problem in which we require to ensure that all the values are atleast K in dictionary. This kind of problem can occur while checking status of start or checking for a bug/action that could have occurred. Let’s discuss certain ways in which this task
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences