Python - How To Check if a Key Exists in a Dictionary in Python

ID : 165

viewed : 60

Tags : PythonPython Dictionary

vote vote

96

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

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 

  • Related HOW TO?