Search for a key by its value in a dictionary in Python
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:
|
1 2 3 4 5 6 7 8 |
# create dictionary {'A': 65, 'B': 66, 'C': 67, … , 'Z': 90} asciiMap = {chr(_): _ for _ in range(65, 91)} # value to search val = 75 # prints K print(next(ch for ch, code in asciiMap.items() if code == val)) |
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.
|
1 2 3 4 5 6 7 8 |
# create dictionary {'A': 65, 'B': 66, 'C': 67, … , 'Z': 90} asciiMap = {chr(_): _ for _ in range(65, 91)} # value to search val = 75 reverseMap = dict(zip(asciiMap.values(), asciiMap.keys())) print(reverseMap.get(val)) # prints K |
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:
|
1 2 3 4 5 6 7 8 |
# create dictionary {'A': 65, 'B': 66, 'C': 67, … , 'Z': 90} asciiMap = {chr(_): _ for _ in range(65, 91)} # value to search val = 75 reverseMap = dict(map(reversed, asciiMap.items())) print(reverseMap.get(val)) # prints K |
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:
|
1 2 3 4 5 6 7 8 9 |
# create dictionary {'A': 65, 'B': 66, 'C': 67, … , 'Z': 90} asciiMap = {chr(_): _ for _ in range(65, 91)} # value to search val = 75 for k, v in asciiMap.items(): if v == val: print(k) # prints K |
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:
|
1 2 3 4 5 6 7 8 9 10 |
# create dictionary {'A': 1, 'B': 1, 'C': 1, 'D': 1, 'E': 1} d = {chr(_): 1 for _ in range(65, 70)} # value to search val = 1 # Create an empty list to store the keys keys = [k for k, v in d.items() if v == val] print(keys) # ['A', 'B', 'C', 'D', 'E'] |
That’s all about searching for a key by its value in a dictionary in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)