![]() |
VOOZH | about |
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.
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.
The original list is : [('Gfg', [1, 3, 4]), ('is', [5, 8, 10]), ('best', [11, 9, 2])]
The required key of list values : GfgMethod 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.
The original list is : [('Gfg', [1, 3, 4]), ('is', [5, 8, 10]), ('best', [11, 9, 2])]
The required key of list values : GfgTime 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:
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 : GfgTime 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:
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 : GfgTime 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.