Home >Backend Development >Python Tutorial >How Can I Perform a Reverse Lookup to Find a Key Based on its Value in a Python Dictionary?
When dealing with dictionaries in programming, it's often necessary to retrieve keys associated with specific values. In this context, you're presented with a function that aims to look up ages in a dictionary and display the corresponding name.
The code you provided raises a KeyError on line 5 because it tries to find the age as a key in the dictionary. To resolve this, you need to search for the age as a value instead.
To address the issue, consider using the keys() and values() methods in Python. These methods allow you to separate the keys and values in the dictionary into separate lists.
The corrected code below demonstrates how to retrieve the key associated with a specified age:
mydict = {'george': 16, 'amber': 19} search_age = raw_input("Provide age") name = mydict.keys()[mydict.values().index(int(search_age))] print(name)
In Python 3.x, you can use the following code:
mydict = {'george': 16, 'amber': 19} search_age = input("Provide age") name = list(mydict.keys())[list(mydict.values()).index(int(search_age))] print(name)
This approach separates the dictionary's values into a list, locates the position of the desired value, and then retrieves the key at that position, successfully completing the reverse lookup. Now, you can retrieve the name associated with any age stored in the dictionary.
The above is the detailed content of How Can I Perform a Reverse Lookup to Find a Key Based on its Value in a Python Dictionary?. For more information, please follow other related articles on the PHP Chinese website!