There are a few ways you can do a reverse dictionary lookup in Python. The easiest way to perform a reverse dictionary lookup in Python is with a for loop.
d = {"name":"Bobby", "age":20,"height":65}
for key, value in d.items():
if value == "Bobby":
print(key)
#Output:
name
You can also invert the dictionary with dictionary comprehension and then access the key/value pair you want directly.
d = {"name":"Bobby", "age":20,"height":65}
d_inverted = {value: key for key, value in d.items()}
print(d_inverted["Bobby"])
#Output:
name
When working with dictionaries in Python, the ability to get information about the items of the dictionary is valuable.
One such situation where you need to do a little more work to access information about items in a dictionary is with a reverse dictionary lookup.
There are a few ways you can do a reverse dictionary lookup in Python. The easiest way to perform a reverse dictionary lookup in Python is with a for loop.
Below is an example showing you how to perform a reverse dictionary lookup using a for loop in your Python code.
d = {"name":"Bobby", "age":20,"height":65}
for key, value in d.items():
if value == "Bobby":
print(key)
#Output:
name
Inverting Dictionary to Perform Reverse Dictionary Lookup in Python
Another way you can perform reverse dictionary lookups is by inverting the dictionary you are working with and then getting the key you want directly via the value.
To invert a dictionary, you can use dictionary comprehension.
Then, after inverting your dictionary, just access the dictionary key/value pair with the value you are looking for.
Below is a simple example showing you how to invert a dictionary and perform a reverse lookup after inversion with Python.
d = {"name":"Bobby", "age":20,"height":65}
d_inverted = {value: key for key, value in d.items()}
print(d_inverted["Bobby"])
#Output:
name
Hopefully this article has been useful for you to learn how to perform reverse dictionary lookups in Python.