• Register
100 points
4

 

In this  kodlogs article will be focusing on the two methods to Check if Key Exists in a Python Dictionary. A Python Dictionary is essentially a facts shape whereby the information objects are saved in a key-value pair. Before you start an article, you should know what a dictionary is and how Python works. Like lists and tuples, dictionaries are also part of the collection. The elements in the dictionary do not have an order. And it also has an index.  The dictionary has to use the { } bracket. It contains the key and the value. In the dictionary we have to tell what the value is and what the key is.  Python in operator essentially exams if a specific component or fee is contained in a specific sequence such as list, tuple, dictionary, etc. 

Four Method

  • For /if value is iterable.
  • Dict.keys( )
  • Dict.get(key,default=None)
  • Dict.has_keys( )

The keys() approach takes no arguments and returns an object that represents a listing of all the keys current in a unique enter dictionary.

So, in order to take a look at whether or not a precise key is existing in the dict, we use Python if declaration alongside with the keys() approach to examine the search_key with the listing of keys back from the keys() method. If the key is present, it will comply with the assertion in the if portion, in any other case it will soar the assertion in the else portion.   Let's get some practical and try to understand more,

Example 1

Inp_dict={'Tania':"T",'Kodlog':,"K",'Tabia':"Z"}
search_key='Kodlog'
If search_key in inp_dict.keys( ):
          Print("The key is present./n")
else:
          Print ("The key does not exist in the dictionary. ")

OUTPUT 
       The key is present. 

Example 2

inp_dict={'Tania':"T",'Kodlog':"K",'Tabia':"Z"}
search_key='Rabia'
If search_key in inp_dict.keys( ):
     Print ("The key is present./n")
else:
     Print ("The key does not exsit in the dictionary. ")


      OUTPUT 
The key does not exsit in the dictionary. 

 

100 points
4