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
test_list = [( 'Gfg' , [ 1 , 3 , 4 ]), ( 'is' , [ 5 , 8 , 10 ]), ( 'best' , [ 11 , 9 , 2 ])]
print ( "The original list is : " + str (test_list))
K = 4
res = [sub[ 0 ] for sub in test_list if K in sub[ 1 ]]
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
test_list = [( 'Gfg' , [ 1 , 3 , 4 ]), ( 'is' , [ 5 , 8 , 10 ]), ( 'best' , [ 11 , 9 , 2 ])]
print ( "The original list is : " + str (test_list))
K = 4
res = list ( filter ( lambda sub, ele = K : ele in sub[ 1 ], test_list))
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
test_list = [( 'Gfg' , [ 1 , 3 , 4 ]), ( 'is' , [ 5 , 8 , 10 ]), ( 'best' , [ 11 , 9 , 2 ])]
print ( "The original list is : " + str (test_list))
K = 4
for sub in test_list:
if K in sub[ 1 ]:
res = sub[ 0 ]
break
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
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
test_list = [( 'Gfg' , [ 1 , 3 , 4 ]), ( 'is' , [ 5 , 8 , 10 ]), ( 'best' , [ 11 , 9 , 2 ])]
print ( "The original list is : " + str (test_list))
K = 4
print ( "The target value is : " + str (K))
res = next ((sub[ 0 ] for sub in test_list if K in sub[ 1 ]), None )
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 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
test_list = [( 'Gfg' , [ 1 , 3 , 4 ]), ( 'is' , [ 5 , 8 , 10 ]), ( 'best' , [ 11 , 9 , 2 ])]
print ( "The original list is : " + str (test_list))
K = 4
print ( "The target value is : " + str (K))
value_to_key_dict = {}
for key, value_list in test_list:
for value in value_list:
value_to_key_dict[value] = key
res = value_to_key_dict.get(K)
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 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 List of Values From Dictionary - Python
We are given a dictionary and our task is to extract all the values from it and store them in a list. For example, if the dictionary is d = {'a': 1, 'b': 2, 'c': 3}, then the output would be [1, 2, 3]. Using dict.values()We can use dict.values() along with the list() function to get the list. Here,
2 min read
Python - Convert key-values list to flat dictionary
We are given a list that contains tuples with the pairs of key and values we need to convert that list into a flat dictionary. For example a = [("name", "Ak"), ("age", 25), ("city", "NYC")] is a list we need to convert it to dictionary so that output should be a flat dictionary {'name': 'Ak', 'age':
3 min read
Python - Tuple value product in dictionary
Sometimes, while working with data, we can have a problem in which we need to find the product of tuple elements that are received as values of dictionary. We may have a problem to get index wise product. Letâs discuss certain ways in which this particular problem can be solved. Method #1 : Using tu
5 min read
Python - Test for Empty Dictionary Value List
Given a dictionary with list as values, check if all lists are empty. Input : {"Gfg" : [], "Best" : []} Output : True Explanation : Both lists have no elements, hence True. Input : {"Gfg" : [], "Best" : [4]} Output : False Explanation : "Best" contains element, Hence False. Method #1 : Using any() +
6 min read
Python - Check for Key in Dictionary Value list
Sometimes, while working with data, we might have a problem we receive a dictionary whose whole key has list of dictionaries as value. In this scenario, we might need to find if a particular key exists in that. Let's discuss certain ways in which this task can be performed. Method #1: Using any() Th
6 min read
Python | Get unique tuples from list
Sometimes, while working with Python list, we can come across a problem in which we require to find the unique occurrences of list. Having elementary data types is easy to handle, but sometime, we might have complex data types and the problem becomes new in that cases. Let's discuss certain ways in
3 min read
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 - Convert tuple list to dictionary with key from a given start value
Given a tuple list, the following article focuses on how to convert it to a dictionary, with keys starting from a specified start value. This start value is only to give a head start, next keys will increment the value of their previous keys. Input : test_list = [(4, 5), (1, 3), (9, 4), (8, 2), (10,
4 min read
Get Unique Values from List of Dictionary
We are given a list of dictionaries and our task is to extract the unique values from these dictionaries, this is common when dealing with large datasets or when you need to find unique information from multiple records. For example, if we have the following list of dictionaries: data = [{'name': 'A
4 min read