Computer Science
Write a Python script to check if a given key already exists in a dictionary.
Answer
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.
Related Questions
Write a Python program to convert a string to a list.
Write a Python script to concatenate the following dictionaries to create a new one:
d1 = {'A': 1, 'B': 2, 'C': 3} d2 = {'D': 4 }
Output should be:
{'A': 1, 'B': 2, 'C': 3, 'D' : 4}
Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and the values are square of keys.
Sample Dictionary
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}
Write a Python script to merge two Python dictionaries.