Check if a Key Exists in a Dictionary in Python

The question of how to check if a given key exists in a Python dictionary falls into the Python membership check topics that you could find more information in the tutorial here.

in keyword is used to do the dictionary membership check. Refer to the code example below

dic = {"A":1, "B":2}

def dicMemberCheck(key, dicObj):
    if key in dicObj:
        print("Existing key")
    else:
        print("Not existing")
        
dicMemberCheck("A")
dicMemberCheck("C")
Existing key
Not existing
Info

You could maybe have other solutions to check the given key exists in the dictionary or not, like,

if key in dicObj.keys()

It could give you the same result as the solution we just showed you. But this dicObj.keys() method is roughly four times slower because it takes extra time to convert the dictionary keys to a list.

You could refer to the execution time performance comparison test below.

>>> import timeit
>>> timeit.timeit('"A" in dic', setup='dic = {"A":1, "B":2}',number=1000000)
0.053480884567733256
>>> timeit.timeit('"A" in dic.keys()', setup='dic = {"A":1, "B":2}',number=1000000)
0.21542178873681905
Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Dictionary

  • Convert a Dictionary to a List in Python
  • Get All the Files of a Directory
  • Find Maximum Value in Python Dictionary