Python: How to check if a key exists in dictionary ?

In this article we will discuss how to check if a key exists in dictionary.
Suppose we have a dictionary of string and int i.e.

wordFreDic = {
    'Hello':56,
    'at':23,
    'test':43,
    'this':78,
}

Now let’s check if key ‘test’ is present in dictionary or not.

Check if key exists in dictionary using in operator

# Check if dict contains any entry with key 'test' 
if "test" in wordFreqDic:
    print("Yes 'test' key exists in dict")
else:
    print("No 'test' key does not exists in dict")    

output

Yes 'test' key exists in dict

check if key exists in dictionary using get()

Dictionary provides a method get() that accepts a key and default value.

dict.get(key[, default])
If given key exists in dictionary then it returns its value,
If given key does not exists in dictionary then it returns the passed default value argument.
If given key does not exists in dictionary and Default value is also not passed in get() function, then get() function will return None.

Let’s use get() this to check if given key exists in dictionary,

'''
Check if key exists in dictionary using get()
'''
if wordFreqDic.get("test") != None:
    print("Yes 'test' key exists in dict")    
else:
    print("No 'test' key does not exists in dict")   

As ‘test’ key exists in the dictionary and its value is not None, so output is,

Yes 'test' key exists in dict

But what if we are call dict.get() with key that exists in the dictionary with value ‘None’ i.e.

Adding key “from” in dict with value None

wordFreqDic["from"] = None

Now wordFreqDic.get(“from”) will return None.

So, we can not be always sure with the result of dict.get() that key exists in dictionary. Therefore, we should use dict.get() to check existence of key in dictionary only in scenarios when we are sure that there can not be an entry of key with given default value.

For example, above dictionary contains occurrence count of given words in an article, so value of keys should always be 0 or more.
So in this scenario, to check if the given key exists in dictionary we should pass -1 as default value in dict.get() i.e.

if wordFreqDic.get("from", -1) != -1:
    print("Yes 'from' key exists in dict")
else:
    print("No 'from' key does not exists in dict")

output

Yes 'from' key exists in dict

Complete example is as follows,

def main():
    
    # Dictionary of string and int
    wordFreqDic = {
        "Hello": 56,
        "at" : 23 ,
        "test" : 43,
        "this" : 78
        }
 
    print(wordFreqDic)
    
    '''
    Check if key exists in dictionary using 'in' operator
    '''
    
    # Check if dict contains any entry with key 'test' 
    if "test" in wordFreqDic:
        print("Yes 'test' key exists in dict")
    else:
        print("No 'test' key does not exists in dict")    
 
    
    '''
    Check if key exists in dictionary using get()
    '''
    if wordFreqDic.get("test") != None:
        print("Yes 'test' key exists in dict")    
    else:
        print("No 'test' key does not exists in dict")     
  
    
    # But what of any element in dictionary has value None i.e.
    
    wordFreqDic["from"] = None
        
    print(wordFreqDic)    
    
    if wordFreqDic.get("from", -1) != -1:
        print("Yes 'from' key exists in dict")
    else:
        print("No 'from' key does not exists in dict")        
    
if __name__ == '__main__':
    main()

output

{'at': 23, 'this': 78, 'test': 43, 'Hello': 56}
Yes 'test' key exists in dict
Yes 'test' key exists in dict
{'from': None, 'at': 23, 'this': 78, 'test': 43, 'Hello': 56}
Yes 'from' key exists in dict
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,418評論 0 10
  • 什么才是真正的旅行身體和心靈一同上路 有句話是這樣說的不在意去哪里在意和誰一起去在行走的過程中和內(nèi)心的聲音對話有興...
    哈哈同學閱讀 127評論 0 0
  • 要想比別人更優(yōu)秀,只有在每一件小事上比功夫---汪中求 1、良好的坐姿、寫姿 這是孩子最易養(yǎng)成,也是家長后悔指數(shù)最...
    阿菊君閱讀 3,459評論 0 3
  • 工作中如果客戶的信息的信息忘記回復,是一件非常尷尬的事情! 現(xiàn)在大家的微信消息都太多,信息一多,就容易忘記回復。 ...
    吳奕鵬閱讀 2,173評論 1 7
  • 虞美人(看落花有感) 繁花簌簌迎風舞,曾憶俏枝頭。晚春芳華盡殘紅,惟有柔枝百繞向晴空。 粉面青衫花下游,抒盡書生意...
    lily_8aed閱讀 446評論 0 1