Skip to content
Related Articles

Related Articles

Python – Extracting Key from Value Substring
  • Last Updated : 10 May, 2020

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 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 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]

 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

My Personal Notes arrow_drop_up
Recommended Articles
Page :