Python - Extract Item with Maximum Tuple Value
Last Updated :
09 Mar, 2023
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract the item with maximum value of value tuple index. This kind of problem can have application in domains such as web development. Let's discuss certain ways in which this task can be performed.
Input : test_dict = {'gfg' : (4, 6), 'is' : (7, 8), 'best' : (8, 2)}, tup_idx = 0 Output : ('best', (8, 2)) Input : test_dict = {'gfg' : (4, 6), 'best' : (8, 2)}, tup_idx = 1 Output : ('gfg' : (4, 6))
Method #1 : Using max() + lambda The combination of above functions can be used to solve this problem. In this, we perform the task of extracting maximum item using max, and value parameter is checked using lambda.
Python3
# Python3 code to demonstrate working of
# Extract Item with Maximum Tuple Value
# Using max() + lambda
# initializing dictionary
test_dict = {'gfg' : (4, 6),
'is' : (7, 8),
'best' : (8, 2)}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing tuple index
# 0 based indexing
tup_idx = 1
# Extract Item with Maximum Tuple Value
# Using max() + lambda
res = max(test_dict.items(), key = lambda ele: ele[1][tup_idx])
# printing result
print("The extracted maximum element item : " + str(res))
Output : The original dictionary is : {'gfg': (4, 6), 'is': (7, 8), 'best': (8, 2)}
The extracted maximum element item : ('is', (7, 8))
Method #2: Using max() + map() + itemgetter() + zip() The combination of above functions can be used to solve this problem. In this, we perform the task of zipping key and required tuple index value extracted using itemgetter() using zip(). Then maximum element is extracted using max().
Python3
# Python3 code to demonstrate working of
# Extract Item with Maximum Tuple Value
# Using max() + map() + itemgetter() + zip()
from operator import itemgetter
# initializing dictionary
test_dict = {'gfg' : (4, 6),
'is' : (7, 8),
'best' : (8, 2)}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing tuple index
# 0 based indexing
tup_idx = 1
# Extract Item with Maximum Tuple Value
# Using max() + map() + itemgetter() + zip()
res = max(zip(test_dict.keys(), map(itemgetter(tup_idx), inventory.values())), key = itemgetter(1))[0]
res = (res, test_dict[res])
# printing result
print("The extracted maximum element item : " + str(res))
Output : The original dictionary is : {'gfg': (4, 6), 'is': (7, 8), 'best': (8, 2)}
The extracted maximum element item : ('is', (7, 8))
Method #3 : Using recursion + for loop()
Approach
We loop through each key-value pair in the given dictionary. For each pair, we check if the length of the tuple value is greater than the given tuple index, and if so, whether the value at that index is greater than the current maximum value found so far. If it is, we update the maximum value and the corresponding item. Finally, we return the item with the maximum tuple value.
Algorithm
1. Define a function max_tuple_value that takes two parameters test_dict and tup_idx.
2. Initialize max_value and max_item to None.
3. Loop through each key-value pair in test_dict:
4. f the length of the tuple value is greater than tup_idx, and the value at that index is greater than the current max_value, update max_value and max_item.
5. Return max_item.
Python3
def max_tuple_value(test_dict, tup_idx):
# Initializing variables
max_value = None
max_item = None
# Looping through the dictionary
for key, value in test_dict.items():
# Checking if the tuple index exists and value is greater than max_value
if len(value) > tup_idx and (max_value is None or value[tup_idx] > max_value):
max_value = value[tup_idx]
max_item = (key, value)
# Returning the item with the maximum tuple value
return max_item
test_dict = {'gfg': (4, 6), 'is': (7, 8), 'best': (8, 2)}
tup_idx = 0
result = max_tuple_value(test_dict, tup_idx)
print(result)
Time Complexity: O(n), where n is the number of key-value pairs in the input dictionary. This is because we loop through each key-value pair once, and the time taken for each iteration is constant.
Auxiliary Space: O(1), as we are only using a constant amount of extra memory to store max_value and max_item. The input dictionary is not modified in any way.
Method #4:Using the reduce() function with a lambda function:
Algorithm:
1.Import the reduce function from the functools module.
2.Create a dictionary containing key-value pairs.
3.Use the reduce function to compare the values of the dictionary items and return the item with the maximum value.
4.Print the maximum value.
Python3
from functools import reduce
test_dict = {'gfg' : (4, 6), 'is' : (7, 8), 'best' : (8, 2)}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
res = reduce(lambda x, y: x if x[1][1] > y[1][1] else y, test_dict.items())
print("The extracted maximum element item : " + str(res))
#This code is contributed by Jyothi pinjala
OutputThe original dictionary is : {'gfg': (4, 6), 'is': (7, 8), 'best': (8, 2)}
The extracted maximum element item : ('is', (7, 8))
Time complexity:
The time complexity of this algorithm is O(n), where n is the number of items in the dictionary. This is because the reduce function iterates over all the items in the dictionary once to find the maximum value.
Auxiliary Space:
The space complexity of this algorithm is O(1), as we are only storing a few variables in memory regardless of the size of the dictionary.
Similar Reads
Python | Get first element with maximum value in list of tuples In Python, we can bind structural information in form of tuples and then can retrieve the same. But sometimes we require the information of tuple corresponding to maximum value of other tuple indexes. This functionality has many applications such as ranking. Let's discuss certain ways in which this
4 min read
Key with Maximum Unique Values - Python The task involves finding the key whose list contains the most unique values in a dictionary. Each list is converted to a set to remove duplicates and the key with the longest set is identified. For example, in d = {"A": [1, 2, 2], "B": [3, 4, 5, 3], "C": [6, 7, 7, 8]}, key "C" has the most unique v
3 min read
Keys with Maximum value - Python In Python, dictionaries are used to store data in key-value pairs and our task is to find the key or keys that have the highest value in a dictionary. For example, in a dictionary that stores the scores of students, you might want to know which student has the highest score. Different methods to ide
4 min read
Python | Tuples with maximum key of similar values Sometimes, while working with Python, we can have a problem in which we need to get all the records. This data can have similar values and we need to find maximum key-value pair. This kind of problem can occur while working with data. Let's discuss certain ways in which this task can be done. Method
6 min read
Python - Minimum in tuple list value 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 minimum of list as tuple attribute. Letâs discuss certai
5 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 certai
8 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
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 | Index Maximum among Tuples Sometimes, while working with records, we might have a common problem of maximizing contents of one tuple with corresponding index of other tuple. This has application in almost all the domains in which we work with tuple records. Letâs discuss certain ways in which this task can be performed. Metho
6 min read
Python | Maximum element in tuple list Sometimes, while working with data in form of records, we can have a problem in which we need to find the maximum element of all the records received. This is a very common application that can occur in Data Science domain. Letâs discuss certain ways in which this task can be performed. Method #1: U
6 min read