Skip to content
Related Articles

Related Articles

Python | Get key from value in Dictionary

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 10 Aug, 2022
Improve Article
Save Article

Let’s see how to get the key by value in Python Dictionary. 

Example: One Liner Code

Python3




# creating a new dictionary
my_dict ={"Java":100, "Python":112, "C":11}
 
# one-liner
print("One line Code Key value: ", list(my_dict.keys())
      [list(my_dict.values()).index(100)])


Output:

Java

Extract Key from Python Dictionary using Value

Method 1: Get the key by value using list comprehension

A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list to get the key from a value in Dictionary.

Python3




dic ={"geeks": "A","for":"B","geeks":"C"}
 
value = {i for i in dic if dic[i]=="B"}
print("key by value:",value)


Output:

key by value: {'for'}

Method 2: Get the key by value using a list.index()

The index() method returns the index of the corresponding value in a list. The approach used here is to find two separate lists of keys and values. Then fetch the key using the position of the value in the val_list. As key at any position N in key_list will have a corresponding value at position N in val_list. 
  

Python3




# creating a new dictionary
my_dict ={"java":100, "python":112, "c":11}
 
# list out keys and values separately
key_list = list(my_dict.keys())
val_list = list(my_dict.values())
 
# print key with val 100
position = val_list.index(100)
print(key_list[position])


Output: 

java

Method 3: Get the key by value using dict.item()

We can also fetch the key from a value by matching all the values using the dict.item() and then print the corresponding key to the given value. 

Python3




# function to return key for any value
def get_key(val):
    for key, value in my_dict.items():
        if val == value:
            return key
 
    return "key doesn't exist"
 
 
# Driver Code
my_dict = {"Java": 100, "Python": 112, "C": 11}
 
print(get_key(100))
print(get_key(11))


Output: 

Java
C

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!