How to Perform a Reverse Dictionary Lookup in Python

09/13/2021

Contents

In this article, you will learn how to perform a reverse dictionary lookup in Python.

Reverse Dictionary Lookup

Performing a reverse dictionary lookup in Python involves finding the key(s) that correspond to a given value. Here’s one way to accomplish this:

# Define the dictionary
my_dict = {'apple': 'fruit', 'carrot': 'vegetable', 'banana': 'fruit'}

# Define the value to look up
value_to_find = 'vegetable'

# Find all keys that match the value
keys = [k for k, v in my_dict.items() if v == value_to_find]

# Print the results
print(keys)

This code defines a dictionary my_dict and a value to look up value_to_find. It then uses a list comprehension to find all keys k in the dictionary where the value v matches the value to find. Finally, it prints the list of keys that match the value.

If the value to find is not in the dictionary, the list of keys will be empty.