Thursday, 1 February 2024

Check for existence of key in a dictionary using in operator in Python

Using the ‘in’ operator in ‘if’ condition, we can check for the existenace of a key in Python Dictionary.

employee = {'id' : 123, 'name' : 'krishna', 'age' : 34}

if 'id' in employee:
    print('id is in employee')
else:
    print('id is not in employee')

Above snippet defines a dictionary named employee with three key-value pairs representing employee information: 'id' with a value of 123, 'name' with a value of 'krishna', and 'age' with a value of 34.

 

Subsequently, an if statement checks whether the key 'id' exists in the dictionary. If the key is present, it prints 'id is in employee'; otherwise, it prints 'id is not in employee'. In this case, since 'id' is indeed a key in the dictionary, the condition evaluates to True, and the first print statement is executed, displaying 'id is in employee' as the output.

 

Find the below working application.

check_for_key_existence.py

employee = {'id' : 123, 'name' : 'krishna', 'age' : 34}

if 'id' in employee:
    print('id is in employee')
else:
    print('id is not in employee')

if 'city' in employee:
    print('city is in employee')
else:
    print('city is not in employee')

Output

id is in employee
city is not in employee


Previous                                                 Next                                                 Home

No comments:

Post a Comment