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 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 program to find the highest 3 values in a dictionary
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Examples: Input : my_dict = {'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69} Output :
5 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
6 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 Program to display keys with same values in a dictionary List
Given a list with all dictionary elements, the task is to write a Python program to extract keys having similar values across all dictionaries. Examples: Input : test_list = [{"Gfg": 5, "is" : 8, "best" : 0}, {"Gfg": 5, "is" : 1, "best" : 0}, {"Gfg": 5, "is" : 0, "best" : 0}] Output : ['Gfg', 'best'
5 min read
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 correspondin
9 min read
Python Program that displays the key of list value with maximum range
Given a Dictionary with keys and values that are lists, the following program displays key of the value whose range in maximum. Range = Maximum number-Minimum number Input : test_dict = {"Gfg" : [6, 2, 4, 1], "is" : [4, 7, 3, 3, 8], "Best" : [1, 0, 9, 3]} Output : Best Explanation : 9 - 0 = 9, Maxim
5 min read
Python Program to extract dictionaries with maximum number of keys
Given a list of dictionaries, the task is to write a Python program to extract a dictionary with a maximum number of keys. Input : test_list = [{'Gfg' : 1}, {'Gfg' : 1, 'is' : 5, 'best' : 4}, {'Gfg' : 2, 'best' : 9}] Output : {'Gfg' : 1, 'is' : 5, 'best' : 4} Explanation : Dictionary with max. lengt
7 min read
Python - Maximum of filtered Keys in dictionary
Sometimes while working with Python dictionaries, we might have a problem in which we require to just maximum 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 comprehe
6 min read
Python program to unique keys count for Value in Tuple List
Given dual tuples, get a count of unique keys for each value present in the tuple. Input : test_list = [(3, 4), (1, 2), (2, 4), (8, 2), (7, 2), (8, 1), (9, 1), (8, 4), (10, 4)] Output : {4: 4, 2: 3, 1: 2} Explanation : 3, 2, 8 and 10 are keys for value 4. Input : test_list = [(3, 4), (1, 2), (8, 1),
6 min read