Sobes.tech
Junior

How can you check if a value exists in a dictionary?

sobes.tech AI

Answer from AI

# Checking for the presence of a key using the 'in' operator
my_dict = {"a": 1, "b": 2, "c": 3}
if "a" in my_dict:
    print("Key 'a' is present")

# Checking for the presence of a key using the .get() method
# The get() method returns None (or a default value) if the key is not found.
# This helps avoid a KeyError.
value = my_dict.get("d")
if value is None:
    print("Key 'd' is missing")
else:
    print(f"Value for key 'd': {value}")

# Checking for the presence of a key using the .keys() method
if "b" in my_dict.keys():
    print("Key 'b' is present")