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
test_dict = { 'gfg' : ( 4 , 6 ),
'is' : ( 7 , 8 ),
'best' : ( 8 , 2 )}
print ("The original dictionary is : " + str (test_dict))
tup_idx = 1
res = max (test_dict.items(), key = lambda ele: ele[ 1 ][tup_idx])
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
from operator import itemgetter
test_dict = { 'gfg' : ( 4 , 6 ),
'is' : ( 7 , 8 ),
'best' : ( 8 , 2 )}
print ("The original dictionary is : " + str (test_dict))
tup_idx = 1
res = max ( zip (test_dict.keys(), map (itemgetter(tup_idx), inventory.values())), key = itemgetter( 1 ))[ 0 ]
res = (res, test_dict[res])
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):
max_value = None
max_item = None
for key, value in test_dict.items():
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)
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 )}
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))
|
Output
The 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
Python | Keys with Maximum value
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 - Extract Unique value key pairs
Sometimes, while working on Python dictionaries, we can have a problem in which we need to perform the extraction of selected pairs of keys from dictionary list, that too unique. This kind of problem can have application in many domains including day-day programming. Let's discuss certain ways in wh
5 min read
Python - Maximum element till K value
One of the problem that is basically a subproblem for many complex problems, finding maximum number till a certain number in list in python, is commonly encountered and this particular article discusses possible solutions to this particular problem. Method #1 : Naive method The most common way this
3 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 - 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 - Row with Minimum difference in extreme values
Given a Matrix, extract the rows with a minimum difference in extreme values. Examples: Input : test_list = [[4, 10, 18], [5, 0], [1, 4, 6], [19, 2]] Output : [[1, 4, 6], [5, 0]] Explanation : 6 - 1 = 5, 5 - 0 = 5, is minimum difference between extreme values. Input : test_list = [[4, 10, 18], [5, 0
4 min read