Home >Backend Development >Python Tutorial >How Can I Find a Dictionary Key Based on its Value in Python?
Retrieving Dictionary Keys Based on Value
When dealing with dictionaries in Python, it is often necessary to locate the key associated with a given value. This scenario arises when you need to find the name of a person based on their age, as in the following example:
dictionary = {'george': 16, 'amber': 19} search_age = input("Provide age: ") # Replace raw_input with input in Python 3
However, the provided code encounters a KeyError because it attempts to directly access the value without first verifying its existence. To rectify this, we employ a more robust approach using the following steps:
Consequently, our code now executes successfully:
mydict = {'george': 16, 'amber': 19} search_age = input("Provide age: ") values_list = list(mydict.values()) if search_age in values_list: value_index = values_list.index(search_age) name = list(mydict.keys())[value_index] print(name) else: print("Age not found.")
The above is the detailed content of How Can I Find a Dictionary Key Based on its Value in Python?. For more information, please follow other related articles on the PHP Chinese website!