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")
        print("Not existing")
Existing key
Not existing

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)
>>> timeit.timeit('"A" in dic.keys()', setup='dic = {"A":1, "B":2}',number=1000000)
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Dictionary

  • Save Dictionary to JSON in Python
  • Convert XML to Dictionary in Python