Use the items() method with for loop to get key from the value in Python dictionary. Fetch key from a value by matching all the values and then print the corresponding key to the given value.
Example dictionary gets key from the value in Python
Simple example code function to return key for any value. This is a custom function.
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": 200, "C": 300}
print(get_key(200))
print(get_key(11))
Output:
Or you can write a list comprehension to pull out the matching keys.
my_dict = {"Java": 100, "Python": 200, "C": 300}
res = ([k for k,v in my_dict.items() if v == 200])
print(res)
How to get the key of a particular value in dictionary python using an index?
Answer: Separates the dictionary’s values in a list, finds the position of the value you have, and gets the key at that position.
my_dict = {"Java": 100, "Python": 200, "C": 300}
res = list(my_dict.keys())[list(my_dict.values()).index(100)]
print(res)
Output: Java
Do comment if you have any doubts or suggestions on this Python dictionary topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.