This post will discuss how to search a key by its value in dictionary in Python.

1. Using Generator Expression

A simple solution is to use a generator expression to search a key by its value in a dictionary. Here’s what the code would look like:

Download  Run Code

2. Using Inverse Dictionary

Another option is to create a dictionary of value-key pairs. We can use the zip() function to bundle together the dictionary’s values and keys and pass the result to the dictionary constructor to get a dictionary.

Download  Run Code

 
This assumes no two keys in the dictionary have the same value, and all dictionary values are hashable. We can simplify the code with the map() function:

Download  Run Code

3. Using for loop

We can even use a for-loop to search for a key by its value by looping over the items of a dictionary and checking if the value matches the given value. For example:

Download  Run Code

4. Using list comprehension

Finally, to get a list of all keys that match the given value, we can use list comprehension. The list comprehension will create a new list of keys that are selected from the dictionary based on a condition. For example, we can search for all the keys having the value 1 in the dictionary using a list comprehension like this:

Download  Run Code

That’s all about searching for a key by its value in a dictionary in Python.