Hello,
today i am gonna teach you a smart way to check if a given key exists in a python dictionary data structure.
If you tried to access a non-existent key in a dictionary python would raise an KeyError exception, the idea here is just to use python's exceptions mechanism to decide if the key exists or not.
Check if a dictionary key exists or not in python.
myDict = {'name':'Adham','job':'Engineer','age':'22'}
try:
myDict['ss'] = 'abc'
print "Dictionary key exists!"
except KeyError :
print "The key dosen't exist , you can handle it now!"
0 comments:
Post a Comment