Dictionary keys() method Python

The Python dictionary keys() method can be used if we want to know all the keys of the dictionary object.This method does not accept any argument.

Link :Python dictionary data type

>>> d=dict( zip("NEW tear" , "Sad love"))
>>> d
{'N': 'S', 'E': 'a', 'W': 'd', ' ': ' ', 't': 'l', 'e': 'o', 'a': 'v', 'r': 'e'}
>>> d.keys()
dict_keys(['N', 'E', 'W', ' ', 't', 'e', 'a', 'r'])
>>> #Testing in empty dictionary object
>>> d1={} #empty dictionary
>>> d1.keys()
>>> d2={ 2:4 , 56:3136 , 934:872356 , 'Tt':'Pp'}
>>> d2.keys()
dict_keys([2, 56, 934, 'Tt'])

The function of keys() method is very straightforward,it return all the keys in the object.

Check if a specific key exist in the dictionary object

There is a way to check is a specific key exist in the dictionary object.To do this we can use the keyword ‘in’.Well I am sure the name ‘in’ itself makes it obvious of what it’s purpose can be.

The format of using ‘in’ is pretty simple.The ‘key’ is placed to the right side followed by the ‘in’ keyword and followed by the sequence of values against which the key is to be checked.The sequence of values in this case can be the values return by calling the method keys().If the key exist then ‘True’ is return if the key doesn’t exist ‘False’ is return.

>>> d=dict( zip("NEW tear" , "Sad love"))
>>> 'W' in d.keys()
>>> 0 in  d.keys()
>>> ' ' in d.keys()
>>> #Checking key in different object
>>> d1={ 'Happy':'New year' , 'Tit':"For tat" , '3.1415':'A pi value' }
>>> 'Happy' in d1.keys()
>>> 'TiT' in d.keys()