Get Keys from a Dictionary by Value in Python

Modified: | Tags: Python, Dictionary

This article explains how to get keys from a dictionary (dict) by value in Python.

To get a value from a dictionary by key, see the following article:

You can get all the keys in a dictionary as a list using the list() function, since iterating over a dictionary yields its keys by default.

d = {'key1': 1, 'key2': 2, 'key3': 3}

print(list(d))
# ['key1', 'key2', 'key3']

Get Keys from a Dictionary by Value Using List Comprehension and items()

You can get dictionary keys based on their values using a list comprehension with the items() method.

For more information on list comprehensions and iterating over dictionaries, refer to the following articles:

The following example shows how to get all keys that have a specific value. If no such key exists, an empty list is returned.

d = {'key1': 'aaa', 'key2': 'aaa', 'key3': 'bbb'}

keys = [k for k, v in d.items() if v == 'aaa']
print(keys)
# ['key1', 'key2']

keys = [k for k, v in d.items() if v == 'bbb']
print(keys)
# ['key3']

keys = [k for k, v in d.items() if v == 'xxx']
print(keys)
# []

To get a single key instead of a list, you can access the first element using [0]. However, if no matching key exists, the list will be empty, and attempting to access [0] will raise an IndexError.

key = [k for k, v in d.items() if v == 'aaa'][0]
print(key)
# key1

key = [k for k, v in d.items() if v == 'bbb'][0]
print(key)
# key3

# key = [k for k, v in d.items() if v == 'xxx'][0]
# print(key)
# IndexError: list index out of range

If you need to perform this operation multiple times, defining a function can be helpful:

def get_keys_from_value(d, val):
    return [k for k, v in d.items() if v == val]

keys = get_keys_from_value(d, 'aaa')
print(keys)
# ['key1', 'key2']

The following version is suitable for dictionaries without duplicate values.

It returns the first matching key if a match is found; otherwise, it returns None. If multiple keys have the same value, only the first one is returned.

def get_key_from_value(d, val):
    keys = [k for k, v in d.items() if v == val]
    if keys:
        return keys[0]
    return None

key = get_key_from_value(d, 'aaa')
print(key)
# key1

key = get_key_from_value(d, 'bbb')
print(key)
# key3

key = get_key_from_value(d, 'xxx')
print(key)
# None

Examples of Extracting Keys Based on Different Conditions

The examples above extract keys that exactly match a specified value.

To extract keys based on different criteria, simply adjust the condition in the list comprehension:

d_num = {'key1': 1, 'key2': 2, 'key3': 3}

keys = [k for k, v in d_num.items() if v >= 2]
print(keys)
# ['key2', 'key3']

keys = [k for k, v in d_num.items() if v % 2 == 1]
print(keys)
# ['key1', 'key3']

d_str = {'key1': 'aaa@xxx.com', 'key2': 'bbb@yyy.net', 'key3': 'ccc@zzz.com'}

keys = [k for k, v in d_str.items() if v.endswith('com')]
print(keys)
# ['key1', 'key3']

Related Categories

Related Articles