Get key by value in dictionary
You can use the in
keyword to check if a value exists in a dictionary, and then use the items()
method to return a list of key-value pairs. Iterate through this list, and check if the value matches the desired value. If it does, return the key. Here's an example:
def get_key(dictionary, value):
for key, val in dictionary.items():
if val == value:
return key
return None
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(get_key(my_dict, 2)) # Output: 'b'
Watch a video course
Python - The Practical Guide
You can also use dictionary comprehension to achieve the same as follows:
def get_key(dictionary, value):
return next((k for k, v in dictionary.items() if v == value), None)
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(get_key(my_dict, 2)) # Output: 'b'
Both of the above examples will return the key associated with the given value in the dictionary. If the value is not found in the dictionary, the function will return None
.