#dictionary - user
user = {
"name": "John",
"email": "[email protected]"
}
#check using has_key
if user.has_key('email'):
print("email key exists in the dictionary")
else:
print("email key does not exist")
#check using in
if 'email' in user:
print "email key exists"
else:
print "email key does not exist"
In the code snippet, there is a dictionary name user which has two key-value pairs. We want to know if the user dictionary has a key email or not. We are checking this by using the has_key() method and in keyword usage.
You can check if a key exists in a dictionary by using has_key() method. It takes the key name as a parameter. For example, if we want to check whether name key exists in the user dictionary we can use below code:
if user.has_key('name'):
print("name key exists")
else:
print("name key does not exist")
You can also check whether a key exists in a dictionary or not using the 'in' keyword. For example, if we want to check whether the name key exists in user dictionary or not, you can below code:
if 'name' in user:
print("name key exists")
else:
print("name key does not exist")
0 Comments