Signup/Sign In
PUBLISHED ON: MARCH 5, 2021

How to find key from value in python dictionary

In the Python programming language, List, Tuple, and Set represent a group of individual objects as a single entity. If we want to represent a group of objects as key-value pairs then we should go for the Dictionary concept. In this tutorial, we will learn how to get keys from values in the python dictionary using the built-in functions such as items() function, comprehension method, and using the for loop by index() method. The items() method returns the list of tuples representing key-value pairs. [(k,v),(k,v),(k,v)].

Example: Find Dictionary Key using Value

The below example shows how to get keys from a specific value.

# dictionary with key value pairs
dict_1 = {100: "python", 200: "Java", 300: "Ruby", 400: "Python", 500: "Python"}
print("Print only keys:")
for i in dict_1:
    print("The key is:",i)
print("Print only values:")
for i in dict_1:
    print("Associated values with keys:",dict_1[i])
print("Getting keys from the specified value")
for i in dict_1:
    if dict_1[i] == "Python":
        print("The keys associated with value", dict_1[i], "is:", i)

Once we run the program, it shows the following result.


Print only keys:
The key is: 100
The key is: 200
The key is: 300
The key is: 400
The key is: 500
Print only values:
Associated values with keys: python
Associated values with keys: Java
Associated values with keys: Ruby
Associated values with keys: Python
Associated values with keys: Python
Getting keys from the specified value
The keys associated with value Python is: 400
The keys associated with value Python is: 500

Example: Using the Comprehension Method

The comprehension concept is also applicable to dictionary data types. This is a simple method, we can get keys from values in a single code.

dict_1={100:"Java",200:"Java",300:"Ruby",400:"Java",500:"Python"} 
x={i for i in dict_1 if dict_1[i]=="Java"}
print("The keys associated with value:",x)

Once we run the code, it shows the following result.


The keys associated with value: {200, 100, 400}

Example: Find key using the item() Method

The below example shows how to get keys from the values using the item() method.

dict_1={100:"Java",200:"Java",300:"Ruby",400:"Java",500:"Python"} 
for k,v in dict_1.items():
    if v=="Java":
        print("The keys are:",k)


The keys are: 100
The keys are: 200
The keys are: 400

Conclusion

In this tutorial, we learned how to get the keys from a value using the python built-in function, comprehension method, and using the for loop.



About the author:
An enthusiastic fresher, a patient person who loves to work in diverse fields. I am a creative person and always present the work with utmost perfection.