note.nkmk.me

Check if the dictionary key / value exists in Python

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

In Python, use the in operator and values(), items() methods of the dictionary object dict to check if a key / value exists in dict (= if a key / value is a member of dict).

  • Check if a key exists in the dictionary: in operator
  • Check if a value exists in the dictionary: in operator, values()
  • Check if a key / value pair exists in the dictionary: in operator, items()

The values() and items() methods are also useful when using a dictionary in a for loop. See the following article.

Sponsored Link

Check if a key exists in the dictionary: in operator

If you use in for a dictionary object, it will return if the key exists. Use not in to check that it does not exist.

d = {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}

print('key1' in d)
# True

print('val1' in d)
# False

print('key4' not in d)
# True

The same is true if you use the keys() method instead of the dictionary object itself. In the case of the above example, the same result is returned by d.keys().

The has_key() method was provided in Python2, but it has been removed in Python3.

To get the value for a key, use dict[key].

print(d['key1'])
# val1

dict[key] will raise an error when the key does not exist, but the get() method returns specified value (default is None) if the key does not exist.

# print(d['key4'])
# KeyError: 'key4'

print(d.get('key4'))
# None

Also, new items can be added with dict[key] = new_value, but the value is overwritten for an existing key. If you want to add an item with a new value only for a new key without changing the value for an existing key, use the setdefault() method. See the following article.

Check if a value exists in the dictionary: in operator, values()

To check if a value exists in the dictionary object, use in for the values() method. Use not in to check that it does not exist.

print('val1' in d.values())
# True

print('val4' not in d.values())
# True

See the following article for how to get the key from the value.

Sponsored Link

Check if a key / value pair exists in the dictionary: in operator, items()

To check if a key / value pair exists in the dictionary object, use in for the items() method. Specify with a key and value tuple (key, value). Use not in to check that it does not exist.

print(('key1', 'val1') in d.items())
# True

print(('key1', 'val2') in d.items())
# False

print(('key1', 'val2') not in d.items())
# True
Sponsored Link
Share

Related Categories

Related Articles