Python | Get key from value in Dictionary
Let’s see how to get the key by value in Python Dictionary.
Example: One Liner Code
Python3
# creating a new dictionarymy_dict ={"Java":100, "Python":112, "C":11}# one-linerprint("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 dictionarymy_dict ={"java":100, "python":112, "c":11}# list out keys and values separatelykey_list = list(my_dict.keys())val_list = list(my_dict.values())# print key with val 100position = 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 valuedef get_key(val): for key, value in my_dict.items(): if val == value: return key return "key doesn't exist"# Driver Codemy_dict = {"Java": 100, "Python": 112, "C": 11}print(get_key(100))print(get_key(11)) |
Output:
Java C


