Skip to content
Related Articles

Related Articles

Improve Article

Python | Search Key from Value

  • Last Updated : 11 Jun, 2021

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 the values and return the corresponding key or keys whose value match. This is the brute force way to perform this particular task.
 

Python3




# Python3 code to demonstrate working of
# Search Key from Value
# Using naive method
 
# initializing dictionary
test_dict = {'Gfg' : 1, 'for' : 2, 'CS' : 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing value
val = 3
 
# Using naive method
# Search key from Value
for key in test_dict:
    if test_dict[key] == val:
        res = key
 
# printing result
print("The key corresponding to value : " + str(res))
Output
The original dictionary is : {'Gfg': 1, 'for': 2, 'CS': 3}
The key corresponding to value : CS

 
Method #2 : Using items() + list comprehension 
This problem can be easily solved using the items(), which is used to extract both keys and values at once, hence making the search easy and can be executed using list comprehension making it a one liner.
 

Python3




# Python3 code to demonstrate working of
# Search Key from Value
# Using items() + list comprehension
 
# initializing dictionary
test_dict = {'Gfg' : 1, 'for' : 2, 'CS' : 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing value
val = 3
 
# Using items() + list comprehension
# Search key from Value
res = [key for key, value in test_dict.items() if value == val]
 
# printing result
print("The key corresponding to value : " + str(res))
Output
The original dictionary is : {'Gfg': 1, 'for': 2, 'CS': 3}
The key corresponding to value : ['CS']

 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 :