Open In App

Python – Find dictionary keys present in a Strings List

Last Updated : 10 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the extraction of dictionary keys from strings list feeded. This problem can have application in many domains including data. Lets discuss certain ways in which this task can be performed. 

Method #1: Using list comprehension This is brute force way in which this task can be performed. In this, we use conditional statements to find the strings matching keys in each string and extract keys from string list. 

Python3




# Python3 code to demonstrate working of
# Extract dictionary keys in Strings List
# Using list comprehension
 
# initializing list
test_list = ["GeeksforGeeks is best for geeks", "I love GeeksforGeeks"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing dictionary
test_dict = {'Geeks' : 5, 'CS' : 6, 'best' : 7, 'love' : 10}
 
# Extract dictionary keys in Strings List
# Using list comprehension
res = [ele if len(ele) > 0 else [None] for ele in [[key for key in test_dict if key in sub]
                                       for sub in test_list]]
                                        
# printing result
print("The matching keys list : " + str(res))


Output : 

The original list is : ['GeeksforGeeks is best for geeks', 'I love GeeksforGeeks']
The matching keys list : [['best', 'Geeks'], ['love', 'Geeks']]

Time complexity: O(NMK), where N is the length of the input list ‘test_list’, M is the maximum length of a string in the ‘test_list’, and K is the number of keys in the ‘test_dict’. This is because the program uses a list comprehension nested inside another list comprehension to iterate over each string in the input list and then iterate over each key in the dictionary to find matches.
Auxiliary space: O(N*M), where N is the length of the input list ‘test_list’ and M is the maximum length of a string in the ‘test_list’. This is because the program creates a new list ‘res’ of the same size as ‘test_list’ to store the results.

Method #2: Using filter() + lambda + list comprehension The combination of above functions can also be used to solve this problem. In this, we perform the task of filtering using filter() and lambda and list comprehension help to reduce one level of nesting. 

Python3




# Python3 code to demonstrate working of
# Extract dictionary keys in Strings List
# Using filter() + lambda + list comprehension
 
# initializing list
test_list = ["GeeksforGeeks is best for geeks", "I love GeeksforGeeks"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing dictionary
test_dict = {'Geeks' : 5, 'CS' : 6, 'best' : 7, 'love' : 10}
 
# Extract dictionary keys in Strings List
# Using filter() + lambda + list comprehension
res = [list(filter(lambda ele: ele in sub, test_dict)) for sub in test_list]
                                        
# printing result
print("The matching keys list : " + str(res))


Output : 

The original list is : ['GeeksforGeeks is best for geeks', 'I love GeeksforGeeks']
The matching keys list : [['best', 'Geeks'], ['love', 'Geeks']]

Time complexity: O(n * m).
Auxiliary space: O(n * m).

Method #3: Using for loop

This program works by iterating through each string in the test_list, and then iterating through each key in the test_dict. If the key is found in the string, it is added to a list of keys for that string. Finally, the list of keys for each string is added to the res list.

Python3




# initializing list
test_list = ["GeeksforGeeks is best for geeks", "I love GeeksforGeeks"]
 
# initializing dictionary
test_dict = {'Geeks': 5, 'CS': 6, 'best': 7, 'love': 10}
 
# Extract dictionary keys in Strings List using for loop
res = []
for string in test_list:
    keys = []
    for key in test_dict:
        if key in string:
            keys.append(key)
    res.append(keys)
 
# printing result
print("The matching keys list : " + str(res))


Output

The matching keys list : [['Geeks', 'best'], ['Geeks', 'love']]

Time complexity: O(n*m*k), where n is the length of test_list, m is the number of keys in test_dict, and k is the average length of each string in test_list.
Auxiliary space: O(n*k), where n is the length of test_list and k is the maximum number of keys that can be present in a single string in test_list. 

Method #4: Using the map() function

This method uses a lambda function with a list comprehension to map the dictionary keys to each string in the list using the map() function. The list() function is then used to convert the map object to a list.

Step-by-step approach:

  • Initialize a list test_list with two strings: “GeeksforGeeks is best for geeks” and “I love GeeksforGeeks”.
  • Initialize a dictionary test_dict with keys “Geeks”, “CS”, “best”, and “love”, and their corresponding values.
  • Create a lambda function map_func that takes a string argument and returns a list of keys from test_dict that are in the string. This is done using a list comprehension that iterates over the keys in test_dict and checks if they are in the string.
  • Use the map() function to apply the lambda function map_func to each string in test_list. This creates a map object that contains a list of matching keys for each string.
  • Convert the map object to a list using the list() function and store it in the variable res.
  • Print the result by converting res to a string using the str() function and concatenating it with a string
  • “The matching keys list: “

Python3




# initializing list and dictionary
test_list = ["GeeksforGeeks is best for geeks", "I love GeeksforGeeks"]
test_dict = {'Geeks': 5, 'CS': 6, 'best': 7, 'love': 10}
 
# create a lambda function to map the keys to the string
map_func = lambda string: [key for key in test_dict if key in string]
 
# use the map() function to apply the lambda function to each string in the list
res = list(map(map_func, test_list))
 
# print the result
print("The matching keys list: " + str(res))


Output

The matching keys list: [['Geeks', 'best'], ['Geeks', 'love']]

Time complexity: O(nm), where n is the length of the list and m is the length of the dictionary. 
Auxiliary space: O(nm) as well, since a new list is created for each string in the list.

Method #5: Using Pandas

Step-by-step approach:

  • Import the pandas library.
  • Initialize the test_list and test_dict.
  • Convert test_list to a dataframe with a single column named “string”.
  • Convert test_dict to a dataframe with two columns named “key” and “value”.
  • Define a matching function that takes a dataframe row as input and returns a list of matching keys.
  • Use the apply method with a lambda function to apply the matching function to each row of the df1 dataframe, and store the results in a new column named “matching_keys”.
  • Convert the “matching_keys” column to a list.
  • Print the result list.

Python3




import pandas as pd
 
# initializing list
test_list = ["GeeksforGeeks is best for geeks", "I love GeeksforGeeks"]
 
# initializing dictionary
test_dict = {'Geeks': 5, 'CS': 6, 'best': 7, 'love': 10}
 
# Convert to dataframes
df1 = pd.DataFrame(test_list, columns=['string'])
df2 = pd.DataFrame(test_dict.items(), columns=['key', 'value'])
 
# Define matching function
def match(row):
    return [key for key in df2['key'] if key in row['string']]
 
# Apply matching function to each row of dataframe
df1['matching_keys'] = df1.apply(lambda row: match(row), axis=1)
 
# Convert result to list
res = df1['matching_keys'].tolist()
 
# printing result
print("The matching keys list : " + str(res))


Output: 

The matching keys list : [['Geeks', 'best'], ['Geeks', 'love']]

Time complexity: O(nkm), where n is the number of strings in test_list, k is the number of keys in test_dict, and m is the average length of a string in test_list.
Auxiliary space: O(n*k), because we store the list of matching keys for each string in the df1 dataframe.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads