Open In App

Python – Extract Item with Maximum Tuple Value

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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)


Output

('best', (8, 2))

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


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.



Last Updated : 09 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads