Check If a Key/Value Exists in a Dictionary in Python

Modified: | Tags: Python, Dictionary

This article explains how to check if a key, value, or key-value pair exists in a dictionary (dict) in Python.

You can also iterate over a dictionary using the values() and items() methods with a for loop. For more details, see the following article:

Check If a Key Exists in a Dictionary: in

To check whether a dictionary contains a specific key, use the in operator. Use not in to check that a key is missing.

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

print('key1' in d)
# True

print('val1' in d)
# False

print('key4' not in d)
# True

You could also write xxx in d.keys(), but this is generally unnecessary because in checks keys by default.

The has_key() method was available in Python 2 but was removed in Python 3. Use the in operator instead.

To retrieve a value from a key, use bracket notation (dict[key]):

print(d['key1'])
# val1

If the key doesn't exist, this raises a KeyError. To avoid that, use the get() method, which returns None by default or a value you specify:

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

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

To add or update an item, use assignment (dict[key] = value). This will overwrite the value if the key already exists. If you only want to add a value when the key is missing (without overwriting an existing one), use the setdefault() method:

Check If a Value Exists in a Dictionary: in, values()

To check whether a specific value exists in a dictionary, use the in operator with the values() method. Use not in to check for absence.

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

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

print('val4' in d.values())
# False

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

To find the key associated with a given value, see the following article:

Check If a Key-Value Pair Exists in a Dictionary: in, items()

To check whether a specific key-value pair exists in a dictionary, use the in operator with the items() method. Specify the pair as a tuple (key, value). Use not in to check that the pair is absent.

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

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

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

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

Related Categories

Related Articles