Chapter 10: Problem 6
How can you determine whether a key-value pair exists in a dictionary?
Short Answer
Expert verified
Answer: You can determine whether a specific key-value pair exists in a Python dictionary by using the 'in' keyword to check if the key is present and then comparing the corresponding value to the known value. Here's an example:
example_dict = {"apple": 5, "banana": 7, "orange": 3}
key_to_check = "apple"
value_to_check = 5
if key_to_check in example_dict:
if example_dict[key_to_check] == value_to_check:
print(f"The key-value pair ({key_to_check}, {value_to_check}) exists in the dictionary.")
else:
print(f"The key {key_to_check} exists, but with a different value.")
else:
print(f"The key {key_to_check} does not exist in the dictionary.")