Python program to find the key of maximum value tuples in a dictionary
Last Updated :
12 Apr, 2023
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 : for
Explanation : 11 is maximum value of tuple and for key "for".
Input : test_dict = {'gfg' : ("a", 13), 'is' : ("c", 9), 'best' : ("k", 10), 'for' : ("p", 1), 'geeks' : ('m', 2)}
Output : gfg
Explanation : 13 is maximum value of tuple and for key "gfg".
Method #1 : Using max() + values() + next()
In this, the maximum of all the tuple values are found using max(), and values are extracted using values(). The next(), is used for iteration using the iterator method of access, and each tuple value is compared with the maximum value.
Python3
# Python3 code to demonstrate working of
# Maximum tuple value key
# Using max() + values() + next()
# initializing dictionary
test_dict = {'gfg': ("a", 3), 'is': ("c", 9), 'best': (
"k", 10), 'for': ("p", 11), 'geeks': ('m', 2)}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# getting maximum value
max_val = max(test_dict.values(), key=lambda sub: sub[1])
# getting key with maximum value using comparison
res = next(key for key, val in test_dict.items() if val == max_val)
# printing result
print("The maximum key : " + str(res))
OutputThe original dictionary is : {'gfg': ('a', 3), 'is': ('c', 9), 'best': ('k', 10), 'for': ('p', 11), 'geeks': ('m', 2)}
The maximum key : for
Time complexity: O(nlogn) where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(1) as only constant extra space is used for storing the variables.
Method #2 : Using list comprehension + max() + values()
In this, we perform the task of getting all the maximum matching values using list comprehension. Getting maximum is done using max().
Python3
# Python3 code to demonstrate working of
# Maximum tuple value key
# Using list comprehension + max() + values()
# initializing dictionary
test_dict = {'gfg': ("a", 3), 'is': ("c", 9), 'best': (
"k", 10), 'for': ("p", 11), 'geeks': ('m', 2)}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# getting maximum value
max_val = max(test_dict.values(), key=lambda sub: sub[1])
# getting key with maximum value using comparison
res = [key for key, val in test_dict.items() if val == max_val][0]
# printing result
print("The maximum key : " + str(res))
OutputThe original dictionary is : {'gfg': ('a', 3), 'is': ('c', 9), 'best': ('k', 10), 'for': ('p', 11), 'geeks': ('m', 2)}
The maximum key : for
Time complexity: O(n*logn) - where n is the number of items in the dictionary.
Auxiliary space: O(n) - as we are creating a new list to store the keys that have the maximum value.
Method #3: Using a for loop to iterate over dictionary items and comparing tuple values
Step-by-step approach:
- Initialize a variable max_val to a tuple with two elements, where the first element is an empty string and the second element is negative infinity. This variable will hold the current maximum value as we iterate over the dictionary.
- Initialize a variable res to an empty string. This variable will hold the key with the maximum value as we iterate over the dictionary.
- Iterate over the dictionary using a for loop that loops over the items in the dictionary.
- For each item, use an if statement to compare the second element of the tuple value to the second element of the max_val variable. If the current tuple value has a greater second element, update max_val to the current tuple value and update res to the current key.
- Print the result using the print() function.
Below is the implementation of the above approach:
Python3
# initializing dictionary
test_dict = {'gfg': ("a", 3), 'is': ("c", 9), 'best': ("k", 10), 'for': ("p", 11), 'geeks': ('m', 2)}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# getting maximum value and key
max_val = ("", float("-inf"))
res = ""
for key, val in test_dict.items():
if val[1] > max_val[1]:
max_val = val
res = key
# printing result
print("The maximum key : " + str(res))
OutputThe original dictionary is : {'gfg': ('a', 3), 'is': ('c', 9), 'best': ('k', 10), 'for': ('p', 11), 'geeks': ('m', 2)}
The maximum key : for
Time complexity: O(n), where n is the number of items in the dictionary.
Auxiliary space: O(1), as we are only using a constant amount of memory to store the max_val and res variables.
Method #4: Using the sorted() function with a lambda function
Step-by-step approach:
- Initialize the dictionary.
- Use the sorted() function with a lambda function to sort the dictionary items based on the second element of the tuple values.
- Get the last item (i.e., the item with the highest second element) from the sorted dictionary.
- Extract the key from the item.
- Print the key.
Below is the implementation of the above approach:
Python3
# initializing dictionary
test_dict = {'gfg': ("a", 3), 'is': ("c", 9), 'best': ("k", 10), 'for': ("p", 11), 'geeks': ('m', 2)}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# getting maximum value and key using sorted() function
max_item = sorted(test_dict.items(), key=lambda x: x[1][1])[-1]
res = max_item[0]
# printing result
print("The maximum key : " + str(res))
OutputThe original dictionary is : {'gfg': ('a', 3), 'is': ('c', 9), 'best': ('k', 10), 'for': ('p', 11), 'geeks': ('m', 2)}
The maximum key : for
Time complexity: O(nlogn) due to the sorting operation.
Auxiliary space: O(n) for the sorted list.
Method #5: Using the reduce() function from functools module
Explanation:
- We first import the reduce() function from the functools module.
- We initialize the dictionary as before.
- The reduce() function takes a function as its first argument and an iterable (in this case, the dictionary keys) as its second argument. The function is applied cumulatively to the items of the iterable from left to right. Here, we use a lambda function that compares the values associated with the keys and returns the key with the maximum value.
- Finally, we print the key with maximum value.
Python3
# Python3 code to demonstrate working of
# Maximum tuple value key
# Using reduce() function
from functools import reduce
# initializing dictionary
test_dict = {'gfg': ("a", 3), 'is': ("c", 9), 'best': (
"k", 10), 'for': ("p", 11), 'geeks': ('m', 2)}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Using reduce() function to find key with maximum value
res = reduce(lambda x, y: x if test_dict[x][1] > test_dict[y][1] else y, test_dict)
# printing result
print("The maximum key : " + str(res))
OutputThe original dictionary is : {'gfg': ('a', 3), 'is': ('c', 9), 'best': ('k', 10), 'for': ('p', 11), 'geeks': ('m', 2)}
The maximum key : for
Time Complexity: The time complexity of this method is O(n), where n is the number of items in the dictionary.
Auxiliary Space: The space complexity of this method is O(1), as we are only storing the key with maximum value and not creating any new data structures.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read