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
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 8,218评论 0赞 10
  • 什么才是真正的旅行身体和心灵一同上路 有句话是这样说的不在意去哪里在意和谁一起去在行走的过程中和内心的声音对话有兴...
    哈哈同学阅读 203评论 0赞 0
  • 要想比别人更优秀,只有在每一件小事上比功夫---汪中求 1、良好的坐姿、写姿 这是孩子最易养成,也是家长后悔指数最...
    阿菊君阅读 3,862评论 0赞 3
  • 工作中如果客户的信息的信息忘记回复,是一件非常尴尬的事情! 现在大家的微信消息都太多,信息一多,就容易忘记回复。 ...
    吴奕鹏阅读 2,440评论 1赞 7
  • 虞美人(看落花有感) 繁花簌簌迎风舞,曾忆俏枝头。晚春芳华尽残红,惟有柔枝百绕向晴空。 粉面青衫花下游,抒尽书生意...
    lily_8aed阅读 558评论 0赞 1

友情链接更多精彩内容