Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Handling missing keys in Python dictionaries
Next article icon

Python - Find dictionary keys present in a Strings List

Last Updated : 10 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
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.


Next Article
Handling missing keys in Python dictionaries
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • How to use a List as a key of a Dictionary in Python 3?
    In Python, we use dictionaries to check if an item is present or not . Dictionaries use key:value pair to search if a key is present or not and if the key is present what is its value . We can use integer, string, tuples as dictionary keys but cannot use list as a key of it . The reason is explained
    3 min read
  • Python | Set 4 (Dictionary, Keywords in Python)
    In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python  In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value c
    5 min read
  • Handling missing keys in Python dictionaries
    In Python, dictionaries are containers that map one key to its value with access time complexity to be O(1). But in many applications, the user doesn't know all the keys present in the dictionaries. In such instances, if the user tries to access a missing key, an error is popped indicating missing k
    4 min read
  • Few mistakes when using Python dictionary
    Usually, A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. Each key-value pair in a Dictionary is separated by a 'colon', whereas each key is separated by a ‘comma’. my_dict = {1: 'Geeks',
    3 min read
  • Remove Key from Dictionary List - Python
    We are given a list of dictionaries and our task is to remove a specific key from each dictionary in the list. For example, if we have the following list: li = [{'Gfg': 1, 'id': 2, 'best': 8}, {'Gfg': 4, 'id': 4, 'best': 10}, {'Gfg': 4, 'id': 8, 'best': 11}] and the key to remove is "id" then the re
    3 min read
  • Python - Keys associated with value list in dictionary
    Sometimes, while working with Python dictionaries, we can have a problem finding the key of a particular value in the value list. This problem is quite common and can have applications in many domains. Let us discuss certain ways in which we can Get Keys associated with Values in the Dictionary in P
    4 min read
  • Iterate through list of dictionaries in Python
    In this article, we will learn how to iterate through a list of dictionaries. List of dictionaries in use: [{'Python': 'Machine Learning', 'R': 'Machine learning'}, {'Python': 'Web development', 'Java Script': 'Web Development', 'HTML': 'Web Development'}, {'C++': 'Game Development', 'Python': 'Game
    3 min read
  • Iterate over a dictionary in Python
    In this article, we will cover How to Iterate Through a Dictionary in Python. To Loop through values in a dictionary you can use built-in methods like values(), items() or even directly iterate over the dictionary to access values with keys. How to Loop Through a Dictionary in PythonThere are multip
    6 min read
  • Python | Check if given multiple keys exist in a dictionary
    A dictionary in Python consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value. Input : dict[] = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3} keys[] = {"geeksforgeeks", "practice"} Output : Yes Input : dict[] = {"geeksforgeeks" : 1, "practice"
    3 min read
  • Count dictionaries in a list in Python
    A list in Python may have items of different types. Sometimes, while working with data, we can have a problem in which we need to find the count of dictionaries in particular list. This can have application in data domains including web development and Machine Learning. Lets discuss certain ways in
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences