CBSE Class 12 Computer Science Question 92 of 120

Review of Python Basics — Question 44

Back to all questions
44
Question

Question 39

Write a Python script to check if a given key already exists in a dictionary.

Solution
my_dict = eval(input("Enter the dictionary: "))
key_check = input("Enter the key to be checked: ")
if key_check in my_dict:
    print("The key", key_check, "exists in the dictionary.")
else:
    print("The key", key_check, "does not exist in the dictionary.")
Output
Enter the dictionary: {'A': 1, 'B': 2, 'C': 3, 'D' : 4} 
Enter the key to be checked: C
The key C exists in the dictionary.

Enter the dictionary: {'A': 1, 'B': 2, 'C': 3, 'D' : 4}
Enter the key to be checked: E
The key E does not exist in the dictionary.
Answer