Python - Extracting Key from Value Substring
Last Updated :
11 Apr, 2023
Sometimes, while working with Python dictionaries, we can have a problem in which we need to find the key from given value, querying substring from key's value. This kind of problem is common and have application in many domains including web development. Lets discuss certain ways in which this task can be performed.
Input : test_dict = {1 : 'Gfg is best', 2 : 'CS is best'} Output : [1, 2] Input : test_dict = {1 : 'best'} Output : [1]
Method #1 : Using loop + items() The combination of above functionalities, can be used to solve this problem. In this, we extract the dictionary values using items() and loop is used to check for substring using "in" operator.
Python3
# Python3 code to demonstrate working of
# Extracting Key from Value Substring
# Using loop + items()
# initializing dictionary
test_dict = {1 : 'Gfg is good', 2 : 'Gfg is best', 3 : 'Gfg is on top'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing search_word
srch_wrd = 'best'
# Extracting Key from Value Substring
# Using loop + items()
res = []
for key, val in test_dict.items():
if srch_wrd in val:
res.append(key)
# printing result
print("The Corresponding key : " + str(res))
Output :
The original dictionary : {1: 'Gfg is good', 2: 'Gfg is best', 3: 'Gfg is on top'} The Corresponding key : [2]
Method #2 : Using list comprehension This is yet another way in which this task can be performed. In this, we perform the above method in one liner in compact way.
Python3
# Python3 code to demonstrate working of
# Extracting Key from Value Substring
# Using list comprehension
# initializing dictionary
test_dict = {1 : 'Gfg is good', 2 : 'Gfg is best', 3 : 'Gfg is on top'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing search_word
srch_wrd = 'best'
# Extracting Key from Value Substring
# Using list comprehension
res = [key for key, val in test_dict.items() if srch_wrd in val]
# printing result
print("The Corresponding key : " + str(res))
Output :
The original dictionary : {1: 'Gfg is good', 2: 'Gfg is best', 3: 'Gfg is on top'} The Corresponding key : [2]
Method #3: Using filter+lambda
Approach
The given problem can be solved by iterating through each key-value pair of the dictionary and checking if the substring srch_wrd is present in the value of each key. If the substring is present, then the corresponding key is appended to the output list. Alternatively, the filter() function can be used to filter the keys of the dictionary based on the condition that the substring srch_wrd is present in the value of each key.
step-by-step Algorithm
1.define a substring
2.define input dictionary
3.use filter and lambda to get the filtered keys
4. make a list with the filtered keys
5. finally print the output
Python3
# Define the substring to search for
srch_wrd = 'best'
# Define the input dictionary
test_dict = {1 : 'Gfg is best', 2 : 'CS is best'}
# Use filter() to create a filtered iterator over the keys of the dictionary
# The lambda function checks if the substring is present in the value of the key
filtered_keys = filter(lambda key: srch_wrd in test_dict[key], test_dict.keys())
# Convert the filtered iterator to a list to get the keys with matching values
output = list(filtered_keys)
# Print the output list
print(output)
Time Complexity: O(N), N is the number of key-value pairs in the dictionary. This is because filter() function is an O(N) operation.
Space complexity: O(K), where K is the number of keys that have a value containing the substring srch_wrd.
METHOD 4:Using def function
APPROACH:
The extract_keys_5 function takes a dictionary and a substring as input and returns a list of keys from the dictionary whose corresponding value contains the substring. The function loops through each key-value pair in the dictionary and checks if the substring is present in the value using the in keyword. If the substring is found in the value, the key is appended to the result list. Finally, the function returns the result list
ALGORITHM:
1. Start
2. Define a function extract_keys_5(dictionary, substring)
3. Create an empty list result = []
4. For each key-value pair in the dictionary using items() method
a. Check if substring is present in the value of each key-value pair using the in operator
b. If the substring is present, append the corresponding key to the result list
5. Return the result list
6. End
Python3
def extract_keys_5(dictionary, substring):
result = []
for k, v in dictionary.items():
if substring in v:
result.append(k)
return result
dictionary = {1: 'Gfg is good', 2: 'Gfg is best'}
substring = 'Gfg is'
result = extract_keys_5(dictionary, substring)
print(result) # Output: [1, 2]
Time Complexity: O(nm), where n is the number of key-value pairs in the dictionary and m is the length of the substring.
Auxiliary Space: O(k), where k is the number of matching keys.
Similar Reads
Python | Extract words from given string
In Python, we sometimes come through situations where we require to get all the words present in the string, this can be a tedious task done using the native method. Hence having shorthand to perform this task is always useful. Additionally, this article also includes the cases in which punctuation
4 min read
Python - Extract K length substrings
The task is to extract all possible substrings of a specific length, k. This problem involves identifying and retrieving those substrings in an efficient way. Let's explore various methods to extract substrings of length k from a given string in PythonUsing List Comprehension List comprehension is t
2 min read
Python - Tuple key detection from value list
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
6 min read
Python - Convert key-value String to dictionary
Sometimes, while working with Python strings, we can have problems in which we need to convert a string's key-value pairs to the dictionary. This can have applications in which we are working with string data that needs to be converted. Let's discuss certain ways in which this task can be performed.
4 min read
Extract Subset of Key-Value Pairs from Python Dictionary
In this article, we will study different approaches by which we can Extract the Subset Of Key-Value Pairs From the Python Dictionary. When we work with Python dictionaries, it often involves extracting subsets of key-value pairs based on specific criteria. This can be useful for tasks such as filter
4 min read
Python - Extract Percentages from String
Given a String, extract all the numbers that are percentages. Input : test_str = 'geeksforgeeks 20% is 100% way to get 200% success' Output : ['20%', '100%', '200%'] Explanation : 20%, 100% and 200% are percentages present. Input : test_str = 'geeksforgeeks is way to get success' Output : [] Explana
2 min read
Python | Search Key from Value
The problem of finding a value from a given key is quite common. But we may have a problem in which we wish to get the back key from the input key we feed. Let's discuss certain ways in which this problem can be solved. Method #1 : Using Naive Method In this method, we just run a loop for each of th
4 min read
Python - Extract digits from given string
We need to extract the digit from the given string. For example we are given a string s=""abc123def456gh789" we need to extract all the numbers from the string so the output for the given string will become "123456789" In this article we will show different ways to extract digits from a string in Py
2 min read
Python - Extract String till Numeric
Given a string, extract all its content till first appearance of numeric character. Input : test_str = "geeksforgeeks7 is best" Output : geeksforgeeks Explanation : All characters before 7 are extracted. Input : test_str = "2geeksforgeeks7 is best" Output : "" Explanation : No character extracted as
5 min read
Python - Extract Indices of substring matches
Given a String List, and a substring, extract list of indices of Strings, in which that substring occurs. Input : test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Gfg is useful"], K = "Gfg" Output : [0, 2, 3] Explanation : "Gfg" is present in 0th, 2nd and 3rd element as substring. Input : tes
5 min read