Python - Tuple key detection from value list
Last Updated :
10 May, 2023
Sometimes, while working with record data, we can have a problem in which we need to extract the key which has matching value of K from its value list. This kind of problem can occur in domains that are linked to data. Lets discuss certain ways in which this task can be performed.
Method #1 : Using List comprehension
This task can be performed using List comprehension. In this, we iterate through each records and test it's value list for K. If found we return that key.
Python3
# Python3 code to demonstrate
# Tuple key detection from value list
# using List comprehension
# Initializing list
test_list = [('Gfg', [1, 3, 4]), ('is', [5, 8, 10]), ('best', [11, 9, 2])]
# printing original list
print("The original list is : " + str(test_list))
# Initializing K
K = 4
# Tuple key detection from value list
# using List comprehension
res = [sub[0] for sub in test_list if K in sub[1]]
# printing result
print ("The required key of list values : " + str(res))
Output : The original list is : [('Gfg', [1, 3, 4]), ('is', [5, 8, 10]), ('best', [11, 9, 2])]
The required key of list values : ['Gfg']
Method #2 : Using filter() + lambda
The combination of above functions can also be used to perform this task. In this, filter() is used to check for existence in list and extract the required key with help of lambda.
Python3
# Python3 code to demonstrate
# Tuple key detection from value list
# using filter() + lambda
# Initializing list
test_list = [('Gfg', [1, 3, 4]), ('is', [5, 8, 10]), ('best', [11, 9, 2])]
# printing original list
print("The original list is : " + str(test_list))
# Initializing K
K = 4
# Tuple key detection from value list
# using filter() + lambda
res = list(filter(lambda sub, ele = K : ele in sub[1], test_list))
# printing result
print ("The required key of list values : " + str(res[0][0]))
Output : The original list is : [('Gfg', [1, 3, 4]), ('is', [5, 8, 10]), ('best', [11, 9, 2])]
The required key of list values : Gfg
Method 3: Using a for loop
This approach uses a for loop to iterate through the elements in the list and check if the value of K is present in the second element of each tuple. If it is found, we break the loop and return the first element of the tuple.
Python3
# Python3 code to demonstrate
# Tuple key detection from value list
# using a for loop
# Initializing list
test_list = [('Gfg', [1, 3, 4]), ('is', [5, 8, 10]), ('best', [11, 9, 2])]
# printing original list
print("The original list is : " + str(test_list))
# Initializing K
K = 4
# Tuple key detection from value list using a for loop
for sub in test_list:
if K in sub[1]:
res = sub[0]
break
# printing result
print ("The required key of list values : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original list is : [('Gfg', [1, 3, 4]), ('is', [5, 8, 10]), ('best', [11, 9, 2])]
The required key of list values : Gfg
Time Complexity: O(n), where n is the number of elements in the list. The for loop runs n times, and the in operator has a time complexity of O(k), where k is the length of the list in the second element of the tuple.
Auxiliary Space: O(1), as we only use a few variables.
Method 4 : using the built-in function any() with a generator expression
Step-by-step approach:
- Initialize the input list of tuples and print it.
- Initialize the target value K and print it.
- Use any() with a generator expression to check if any of the tuples contains the value K. If so, store the corresponding key in a variable res.
- Print the result.
Python3
# Initializing list
test_list = [('Gfg', [1, 3, 4]), ('is', [5, 8, 10]), ('best', [11, 9, 2])]
# printing original list
print("The original list is : " + str(test_list))
# Initializing K
K = 4
# printing target value
print("The target value is : " + str(K))
# Tuple key detection from value list using any() with generator expression
res = next((sub[0] for sub in test_list if K in sub[1]), None)
# printing result
print ("The required key of list values : " + str(res))
OutputThe original list is : [('Gfg', [1, 3, 4]), ('is', [5, 8, 10]), ('best', [11, 9, 2])]
The target value is : 4
The required key of list values : Gfg
Time complexity: O(n) in the worst case, where n is the length of the input list.
Auxiliary space: O(1) because we only need to store a few variables (test_list, K, res) regardless of the input size.
Method 5: Using a dictionary
Step-by-step approach:
- Initialize an empty dictionary value_to_key_dict.
- Loop through each element of the test_list using a for loop.
- Within the loop, loop through the sublist and map each value to its corresponding key in the original list by adding an entry to value_to_key_dict with the value as the key and the corresponding key from the original list as the value.
- Use the get method of the dictionary to check if K exists in the keys of value_to_key_dict. If it does, return the corresponding value from the dictionary, which will be the key from the original list.
- If K is not found, return None.
- Print the result.
Python3
# Initializing list
test_list = [('Gfg', [1, 3, 4]), ('is', [5, 8, 10]), ('best', [11, 9, 2])]
# printing original list
print("The original list is : " + str(test_list))
# Initializing K
K = 4
# printing target value
print("The target value is : " + str(K))
# Using a dictionary to map values to keys
value_to_key_dict = {}
for key, value_list in test_list:
for value in value_list:
value_to_key_dict[value] = key
# Check if K exists in the keys of the dictionary
res = value_to_key_dict.get(K)
# printing result
print ("The required key of list values : " + str(res))
OutputThe original list is : [('Gfg', [1, 3, 4]), ('is', [5, 8, 10]), ('best', [11, 9, 2])]
The target value is : 4
The required key of list values : Gfg
Time complexity: O(n*m), where n is the length of the original list and m is the maximum length of the sublists.
Auxiliary space: O(n*m), where n and m are as defined above, because we need to store each value and its corresponding key in the dictionary.
Similar Reads
Get all Tuple Keys from Dictionary - Python In Python, dictionaries can have tuples as keys which is useful when we need to store grouped values as a single key. Suppose we have a dictionary where the keys are tuples and we need to extract all the individual elements from these tuple keys into a list. For example, consider the dictionary : d
3 min read
Python | Filter Tuple Dictionary Keys Sometimes, while working with Python dictionaries, we can have itâs keys in form of tuples. A tuple can have many elements in it and sometimes, it can be essential to get them. If they are a part of a dictionary keys and we desire to get filtered tuple key elements, we need to perform certain functi
4 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 - Check if variable is tuple We are given a variable, and our task is to check whether it is a tuple. For example, if the variable is (1, 2, 3), it is a tuple, so the output should be True. If the variable is not a tuple, the output should be False.Using isinstance()isinstance() function is the most common and Pythonic way to c
2 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