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
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read