How to get the key corresponding to a value in a Python dictionary?
Published on Aug. 22, 2023, 12:17 p.m.
To get the key corresponding to a value in a Python dictionary, you can use a dictionary comprehension or loop through the key-value pairs in the dictionary. Here are some examples:
Using a dictionary comprehension:
my_dict = {'key1': 10, 'key2': 45, 'key3': 23}
search_value = 45
result = [key for key, value in my_dict.items() if value == search_value]
if result:
print("Key(s) for the value:", result)
else:
print("Value does not exist in dictionary")
In this example, a dictionary comprehension is used to create a list of keys that have the value 45
. If the resulting list is non-empty, it means that one or more keys with the given value exist in the dictionary.
Using a for-loop:
my_dict = {'key1': 10, 'key2': 45, 'key3': 23}
search_value = 45
result = []
for key, value in my_dict.items():
if value == search_value:
result.append(key)
if result:
print("Key(s) for the value:", result)
else:
print("Value does not exist in dictionary")
In this example, a for-loop is used to loop through the key-value pairs in the dictionary and append the keys that have the value 45
to a list. If the resulting list is non-empty, it means that one or more keys with the given value exist in the dictionary.
Note that if the dictionary contains duplicate values, both methods above will return a list of keys. If you only want to get the first key that matches the value, you can modify the code to break out of the loop or return the first element of the resulting list, depending on your preferences.