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 code to demonstrate working of # Extract dictionary keys in Strings List# Using list comprehension # initializing listtest_list = ["GeeksforGeeks is best for geeks", "I love GeeksforGeeks"] # printing original listprint("The original list is : " + str(test_list)) # initializing dictionarytest_dict = {'Geeks' : 5, 'CS' : 6, 'best' : 7, 'love' : 10} # Extract dictionary keys in Strings List# Using list comprehensionres = [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)) |
The original list is : ['GeeksforGeeks is best for geeks', 'I love GeeksforGeeks'] The matching keys list : [['best', 'Geeks'], ['love', 'Geeks']]
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 code to demonstrate working of # Extract dictionary keys in Strings List# Using filter() + lambda + list comprehension # initializing listtest_list = ["GeeksforGeeks is best for geeks", "I love GeeksforGeeks"] # printing original listprint("The original list is : " + str(test_list)) # initializing dictionarytest_dict = {'Geeks' : 5, 'CS' : 6, 'best' : 7, 'love' : 10} # Extract dictionary keys in Strings List# Using filter() + lambda + list comprehensionres = [list(filter(lambda ele: ele in sub, test_dict)) for sub in test_list] # printing result print("The matching keys list : " + str(res)) |
The original list is : ['GeeksforGeeks is best for geeks', 'I love GeeksforGeeks'] The matching keys list : [['best', 'Geeks'], ['love', 'Geeks']]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


