If a key exists in a dictionary python

Check if a given key already exists in a dictionary

To get the idea how to do that we first inspect what methods we can call on dictionary.

Here are the methods:

d={'clear':0, 'copy':1, 'fromkeys':2, 'get':3, 'items':4, 'keys':5, 'pop':6, 'popitem':7, 'setdefault':8, 'update':9, 'values':10}

Python Dictionary clear()        Removes all Items
Python Dictionary copy()         Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys()     Creates dictionary from given sequence
Python Dictionary get()          Returns Value of The Key
Python Dictionary items()        Returns view of dictionary (key, value) pair
Python Dictionary keys()         Returns View Object of All Keys
Python Dictionary pop()          Removes and returns element having given key
Python Dictionary popitem()      Returns & Removes Element From Dictionary
Python Dictionary setdefault()   Inserts Key With a Value if Key is not Present
Python Dictionary update()       Updates the Dictionary
Python Dictionary values()       Returns view of all values in dictionary

The brutal method to check if the key already exists may be the get() method:

d.get("key")

The other two interesting methods items() and keys() sounds like too much of work. So let's examine if get() is the right method for us. We have our dict d:

d= {'clear':0, 'copy':1, 'fromkeys':2, 'get':3, 'items':4, 'keys':5, 'pop':6, 'popitem':7, 'setdefault':8, 'update':9, 'values':10}

Printing shows the key we don't have will return None:

print(d.get('key')) #None
print(d.get('clear')) #0
print(d.get('copy')) #1

We use that to get the information if the key is present or no. But consider this if we create a dict with a single key:None:

d= {'key':None}
print(d.get('key')) #None
print(d.get('key2')) #None

Leading that get() method is not reliable in case some values may be None.

This story should have a happier ending. If we use the in comparator:

print('key' in d) #True
print('key2' in d) #False

We get the correct results.

We may examine the Python byte code:

import dis
dis.dis("'key' in d")
#   1           0 LOAD_CONST               0 ('key')
#               2 LOAD_NAME                0 (d)
#               4 COMPARE_OP               6 (in)
#               6 RETURN_VALUE

dis.dis("d.get('key2')")
#   1           0 LOAD_NAME                0 (d)
#               2 LOAD_METHOD              1 (get)
#               4 LOAD_CONST               0 ('key2')
#               6 CALL_METHOD              1
#               8 RETURN_VALUE

This shows that in compare operator is not just more reliable, but even faster than get().

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")

Output:

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

How do you check if a key exists in a dictionary Python?

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.

How do you check if a key value pair exists in a dictionary Python?

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.

Which operator tests to see 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.

What is the keyword that is used to check if a particular key exists in a dictionary?

The “in” Keyword When querying a dictionary, the keys, and not the values, are searched.