Skip to content

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:

Get a key by value in a Python dictionary

python
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'

<div class="alert alert-info flex not-prose"> Watch a course Python - The Practical Guide</div>

You can also use dictionary comprehension to achieve the same as follows:

Get a key by value in a Python dictionary using dictionary comprehension

python
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.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.