Home >Backend Development >Python Tutorial >How to Handle `KeyError` When Performing Reverse Lookups in Python Dictionaries?

How to Handle `KeyError` When Performing Reverse Lookups in Python Dictionaries?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-14 01:27:111010browse

How to Handle `KeyError` When Performing Reverse Lookups in Python Dictionaries?

Reverse Lookups in Python Dictionaries: Retrieving Keys by Values

While Python dictionaries provide an efficient way to map keys to their corresponding values, there may be situations where you need to perform reverse lookups. This can come in handy for scenarios where you have a value and need to find the associated key.

Question:

Suppose you have a dictionary that maps names to ages. Your task is to create a function that takes an age as input and returns the corresponding name. However, your script is encountering a KeyError error, and you're seeking assistance in modifying the code to handle this case.

Code:

dictionary = {'george': 16, 'amber': 19}
search_age = raw_input("Provide age")
for age in dictionary.values():
    if age == search_age:
        name = dictionary[age]
        print name

Solution:

The provided code attempts to iterate through the values of the dictionary and compare them with the input age. If a match is found, the code tries to retrieve the matching key from the dictionary using dictionary[age], which is where the KeyError occurs.

To perform reverse lookups in Python, we can utilize two methods:

Method 1:

mydict = {'george': 16, 'amber': 19}
print mydict.keys()[mydict.values().index(16)]  # Prints george

This approach involves obtaining a list of all keys and values using mydict.keys() and mydict.values(), respectively. We then use index() on the values list to find the position of the input age and retrieve the key at that position.

Method 2 (Python 3.x):

mydict = {'george': 16, 'amber': 19}
print(list(mydict.keys())[list(mydict.values()).index(16)])  # Prints george

Similar to the first method, this approach involves converting keys and values to lists. However, it leverages Python 3.x syntax to simplify the indexing process.

The above is the detailed content of How to Handle `KeyError` When Performing Reverse Lookups in Python Dictionaries?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn