Searching for a key in a dictionary

Searching for a key in a dictionary

There is no pre-defined function to search for keys in dictionary. We have to use if condition to check if a particular key is part of dictionary or not.

------------------------------

name = {1:"TalentEve",2:"Embeddeddesignblog",3:"YouTube-Way2Know",4:"Myvision-thisworld"}

if 2 in name.keys():
    print(name[2])
else:
    print("Key not found")

For the above code, output shall be Embeddeddesignblog as 2 is a key in the dictionary

------------------------------

The previous versions of python has has_key() method to check for a particular key in a dictionary


Post a Comment

0 Comments