You can use the _________ operator to determine whether a key exists in a dictionary.

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

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

The values() and items() methods are also used to iterate a dictionary with for loop. See the following article.

  • Iterate dictionary (key and value) with for loop in Python

Check if a key exists in a dictionary: in operator

Using the in operator for a dictionary object itself returns if a key exists, i.e., if a dictionary has/contains a key. Use not in to check if a key does not exist in a dictionary.

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 xxx in d.keys().

The has_key() method was provided in Python 2, but was removed in Python 3.

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

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

  • Get value from dictionary by key with get() in Python

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

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

You can also add a new item with dict[key] = new_value. 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.

  • Add an item only when the key does not exist in dict in Python (setdefault())

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

To check if a value exists in a dictionary, i.e., if a dictionary has/contains a value, use the in operator and the values() method. Use not in to check if a value does not exist in a dictionary.

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.

  • Get key from value in dictionary in Python

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

To check if a key-value pair exists in a dictionary, i.e., if a dictionary has/contains a pair, use the in operator and the items() method. Specify a tuple (key, value). Use not in to check if a pair does not exist in a dictionary.

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

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

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

Given a dictionary in Python our task is to check whether the given key is already present in the dictionary or not.  If present, print “Present” and the value of the key. Otherwise, print “Not present”. 

Example

Input : {‘a’: 100, ‘b’:200, ‘c’:300}, key = b
Output : Present, value = 200

Input : {‘x’: 25, ‘y’:18, ‘z’:45}, key = w
Output : Not present

There can be different ways for checking if the key already exists, we have covered the following approaches:

  • Using the Inbuilt method keys() 
  • Using if and in
  • Using has_key() method
  • Using get() method

Check If Key Exists using the Inbuilt method keys() 

Using the Inbuilt method keys() method returns a list of all the available keys in the dictionary. With the Inbuilt method keys(), use if statement with ‘in’ operator to check if the key is present in the dictionary or not. 

Python3

def checkKey(dic, key):

    if key in dic.keys():

        print("Present, ", end =" ")

        print("value =", dic[key])

    else:

        print("Not present")

dic = {'a': 100, 'b':200, 'c':300}

key = 'b'

checkKey(dic, key)

key = 'w'

checkKey(dic, key)

Output

Present,  value = 200
Not present

Check If Key Exists using if and in

This method uses the if statement to check whether the given key exists in the dictionary. 

Python3

def checkKey(dic, key):

    if key in dic:

        print("Present, ", end =" ")

        print("value =", dic[key])

    else:

        print("Not present")

dic = {'a': 100, 'b':200, 'c':300}

key = 'b'

checkKey(dic, key)

key = 'w'

checkKey(dic, key)

Output

Present,  value = 200
Not present

Check If Key Exists using has_key() method

Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not. 

Note – has_keys() method has been removed from the Python3 version. Therefore, it can be used in Python2 only. 

Python

def checkKey(dic, key):

    if dic.has_key(key):

        print("Present, value =", dic[key])

    else:

        print("Not present")

dic = {'a': 100, 'b':200, 'c':300}

key = 'b'

checkKey(dic, key)

key = 'w'

checkKey(dic, key)

Output

('Present, value =', 200)
Not present

Check If Key Exists using get()

Using the Inbuilt method get() method returns a list of available keys in the dictionary. With the Inbuilt method keys(), use the if statement to check if the key is present in the dictionary or not. If the key is present it will print “Present” Otherwise it will print “Not Present”.

Python3

dic = {'a': 100, 'b':200, 'c':300}

if dic.get('b') == None:

  print("Not Present")

else:

  print("Present")

Handling ‘KeyError’ Exception

Use try and except to handle the KeyError exception to determine if a key is present in a dict. The KeyError exception is generated if the key you’re attempting to access is not present in the dictionary.

Python3

dictExample = {'Aman': 110, 'Rajesh': 440, 'Suraj': 990}

print("Example 1")

try:

    dictExample["Kamal"]

    print('The key exists in the dictionary')

except KeyError as error:

    print("The key doesn't exist in the dictionary")

print("Example 2")

try:

    dictExample["Suraj"]

    print('The key exists in the dictionary')

except KeyError as error:

    print("The given key doesn't exist in the dictionary")

Output

Example 1
The key doesn't exist in the dictionary
Example 2
The key exists in the dictionary

Using count() method

count() method can be used to check if the key exists in the dictionary, if the count of the key is 1 then the key is present else not.

Python3

dic = {'a': 100, 'b': 200, 'c': 300}

key = 'b'

x = list(dic.keys())

res = "Not Present"

if(x.count(key) == 1):

    res = "Present"

print(res)


Which operator is used to determine if a key exists in a dictionary?

The simplest way to check if a key exists in a dictionary is to use the in operator. It's a special operator used to evaluate the membership of a value. This is the intended and preferred approach by most developers.

How can you determine whether a key

To check if a key-value pair exists in a dictionary, i.e., if a dictionary has/contains a pair, use the in operator and the items() method. Specify a tuple (key, value) . Use not in to check if a pair does not exist in a dictionary.

What can be used as a key in a dictionary?

Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable.

Which keyword is used to test for a membership of a key in a dictionary?

We can test if a key is in a dictionary or not using the keyword in .