There are multiple ways to see if key exists in Python dictionary or not, like using keys(), has_key(), get(), Try and Except.
To me Try and Except is a best and more efficient way in python to check if a key exists in dictionary because it provides an appropriate way of handling unexpected errors without interrupting the code flow.
Now I'm sharing a code snippet showing the way to use Try and Except block to check a key in Python dictionary.
In this code, I have created one function "key_check" which basically accepts a dictionary and a key where we will check the existence of a key in that dictionary.
If the key is present in the dictionary this function will return true else false.
For example: for Key='Name'. This function will return true and print 'Name' exists.
def key_check(mydict, key):
#Python function to check if key in dictionary already exists
try:
mydict[key]
return True
except KeyError:
return False
def main():
#createing a dictionary
mydict = {
"Name": "Python",
"Hello": "World",
"Version": 3
}
# key to check
key = 'Name'
print('calling key check function in if block')
if key_check(mydict, key):
print("'%s' exists"%key)
else:
print("'%s' does not exists"%key)
if __name__ == '__main__':
main()
I hope that you find this helpful.
No comments:
Post a Comment