Python find key in list

Get key from value in dictionary in Python

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

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
source: dict_get_key_from_value.py

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.

  • Get dictionary value from key with get[] in Python

You can also use the keys[] method to get a list of all keys.

  • Iterate keys and values of dict with for loop in Python
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.

  • List comprehensions in Python
  • Iterate keys and values of dict with for loop in Python

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'}
source: dict_get_key_from_value.py
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] # []
source: dict_get_key_from_value.py

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
source: dict_get_key_from_value.py

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']
source: dict_get_key_from_value.py

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
source: dict_get_key_from_value.py

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': '', 'key2': '', 'key3': ''} keys = [k for k, v in d_str.items[] if v.endswith['com']] print[keys] # ['key1', 'key3']
source: dict_get_key_from_value.py
Sponsored Link
Share
Tweet

Related Categories

  • Python
  • Dictionary

Related Articles

  • Add an item only when the key does not exist in dict in Python [setdefault[]]
  • Unpack and pass list, tuple, dict to function arguments in Python
  • Iterate keys and values of dict with for loop in Python
  • Remove an item from a dictionary in Python [clear, pop, popitem, del]
  • Pretty-print with pprint in Python
  • Create a dictionary in Python [{}, dict[], dict comprehensions]
  • Check if the dictionary key / value exists in Python
  • Merge multiple dictionaries and add items to a dictionary in Python
  • Get dictionary value from key with get[] in Python
  • Change dictionary key in Python
  • Set operations on multiple dictionary keys in Python
  • Sort a list of dictionaries by the value of the specific key in Python
  • Python, Pillow: Rotate image
  • Get the fractional and integer parts with math.modf[] in Python
  • pandas: Rename columns / index names [labels] of DataFrame

Video liên quan

Chủ Đề