Python | Tuples with maximum key of similar values
Last Updated :
12 Apr, 2023
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 #1: Using max() + groupby() + itemgetter() + list comprehension The combination of above functions can be used to perform this particular task. In this, we first group the like valued elements using groupby() and itemgetter(), and then extract the maximum of those using max() and cumulate the result in list using list comprehension.
Python3
from operator import itemgetter
from itertools import groupby
test_list = [( 4 , 3 ), ( 2 , 3 ), ( 3 , 10 ), ( 5 , 10 ), ( 5 , 6 )]
print ( "The original list : " + str (test_list))
res = [ max (values) for key, values in groupby(test_list, key = itemgetter( 1 ))]
print ( "The records retaining maximum keys of similar values : " + str (res))
|
Output
The original list : [(4, 3), (2, 3), (3, 10), (5, 10), (5, 6)]
The records retaining maximum keys of similar values : [(4, 3), (5, 10), (5, 6)]
Time complexity: O(n log n), where n is the length of the input list. This is because the groupby() function requires the list to be sorted, which takes O(n log n) time, and the max() function needs to iterate through each group, which takes O(n) time.
Auxiliary space: O(n), where n is the length of the input list. This is because the groupby() function creates a new list of groups, which could potentially have n elements if every tuple in the input list has a unique second element. The res list also has n elements in the worst case, if every group contains only one tuple.
Method #2: Using setdefault() + items() + loop + list comprehension The combination of above functions can also achieve this task. In this, we convert the list tuple key-value pairs into a dictionary and assign a default value using setdefault(). The final result is computed using list comprehension.
Python3
test_list = [( 4 , 3 ), ( 2 , 3 ), ( 3 , 10 ), ( 5 , 10 ), ( 5 , 6 )]
print ( "The original list : " + str (test_list))
temp = {}
for val, key in test_list:
if val > temp.setdefault(key, val):
temp[key] = val
res = [(val, key) for key, val in temp.items()]
print ( "The records retaining maximum keys of similar values : " + str (res))
|
Output :
The original list : [(4, 3), (2, 3), (3, 10), (5, 10), (5, 6)]
The records retaining maximum keys of similar values : [(4, 3), (5, 10), (5, 6)]
Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using setdefault() + items() + loop + list comprehension which has a time complexity of O(n*n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method #3: Using dict.fromkeys(): We can use dict.fromkeys() to find the tuples with maximum key of similar values by first creating a dictionary with the unique second elements of the tuples as the keys and the first elements as the values. Then we can iterate through the list of tuples and update the dictionary with the maximum key-value pair.
Here is an example of how to use dict.fromkeys() to find the tuples with maximum key of similar values:
Python3
test_list = [( 4 , 3 ), ( 2 , 3 ), ( 3 , 10 ), ( 5 , 10 ), ( 5 , 6 )]
print ( "The original list : " + str (test_list))
temp = dict .fromkeys( set (x[ 1 ] for x in test_list), 0 )
for x in test_list:
if x[ 0 ] > temp[x[ 1 ]]:
temp[x[ 1 ]] = x[ 0 ]
res = [(val, key) for key, val in temp.items()]
print ( "The records retaining maximum keys of similar values : " + str (res))
|
Output
The original list : [(4, 3), (2, 3), (3, 10), (5, 10), (5, 6)]
The records retaining maximum keys of similar values : [(5, 10), (4, 3), (5, 6)]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using defaultdict() and loop
Use the defaultdict class from the collections module to create a dictionary with default value as an empty list. Then, loop through the original list and append each tuple to the list corresponding to its second element (i.e., key) in the dictionary. Finally, loop through the dictionary and for each key, we sort the list of tuples by their first element (i.e., value) in descending order and take the first tuple as the result.
Python
from collections import defaultdict
test_list = [( 4 , 3 ), ( 2 , 3 ), ( 3 , 10 ), ( 5 , 10 ), ( 5 , 6 )]
print ( "The original list : " + str (test_list))
temp = defaultdict( list )
for val, key in test_list:
temp[key].append((val, key))
res = [( sorted (lst, reverse = True )[ 0 ]) for lst in temp.values()]
print ( "The records retaining maximum keys of similar values : " + str (res))
|
Output
The original list : [(4, 3), (2, 3), (3, 10), (5, 10), (5, 6)]
The records retaining maximum keys of similar values : [(5, 10), (4, 3), (5, 6)]
Time complexity: O(n*logn) where n is the length of the input list because of the sorting step.
Auxiliary space: O(n) for the dictionary.
Similar Reads
Python - Maximum of Similar Keys in Tuples
Sometimes, while working with Python tuples, we can have a problem in which we need to perform maximum of all values of the equal keys in Tuple list. This kind of application in useful in many domains such as web development and day-day programming. Let's discuss certain ways in which this task can
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 - Extract Item with Maximum Tuple Value
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 :
5 min read
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
Python - Find the Maximum of Similar Indices in two list of Tuples
Sometimes, while working with Python records, we can have a problem in which we need to perform cross maximization of list of tuples. This kind of application is popular in web development domain. Letâs discuss certain ways in which this task can be performed. Method #1 : Using list comprehension +
7 min read
Python - Pairs with multiple similar values in dictionary
Sometimes, while working with dictionaries, we can have a problem in which we need to keep the dictionaries which are having similar key's value in other dictionary. This is a very specific problem. This can have applications in web development domain. Lets discuss certain ways in which this task ca
4 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 group keys with similar values in a dictionary
Given a dictionary with values as a list. Group all the keys together with similar values. Input : test_dict = {"Gfg": [5, 6], "is": [8, 6, 9], "best": [10, 9], "for": [5, 2], "geeks": [19]} Output : [['Gfg', 'is', 'for'], ['is', 'Gfg', 'best'], ['best', 'is'], ['for', 'Gfg']] Explanation : Gfg has
2 min read
Python - Summation of tuple dictionary values
Sometimes, while working with data, we can have a problem in which we need to find the summation of tuple elements that are received as values of dictionary. We may have a problem to get index wise summation. Letâs discuss certain ways in which this particular problem can be solved. Method #1: Using
4 min read