note.nkmk.me

Get key from value in dictionary in Python

Posted: 2020-12-12 / Tags: Python, Dictionary

This article describes how to get a key from a value in a dictionary (dict type object) in Python.

  • Get key from value with list comprehension and items()
  • Sample codes to extract keys with various conditions

To get the value from the key, just specify the key as follows.

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

value = d['key1']
print(value)
# aaa

You can also use the get() method to get the value from the key. If you use the get() method, no error will occur even if you specify a key that does not exist. See the following article.

You can also use the keys() method to get a list of all keys.

Sponsored Link

Get key from value with list comprehension and items()

To get the key from the value in the dictionary, use list comprehension and items() method.

For list comprehensions and for loops for dictionaries, see the following articles.

The following is a sample code to get a list of keys that are paired with a specified value. If the key with the specified value does not exist, 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)
# []

If you want to get the key itself instead of the list, you can specify the first element of the list with [0].

Note that if a key with the specified value does not exist, it will be an empty list, so specifying [0] will raise 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 repeat the same operation, it is useful to make it a function.

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

For dictionaries that do not have duplicate values, the following function is also possible.

If a key with the specified value exists, that key is returned, otherwise None is returned. If the values are duplicated, one of the keys 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

Sample codes to extract keys with various conditions

In the above example, keys whose value is equal to the specified value are extracted.

You can extract keys under various conditions by changing the conditional expression part of 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']
Sponsored Link
Share

Related Categories

Related Articles