my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"} # Check if "key1" is in the dictionary if "key1" in my_dict: print("Key1 exists in the dictionary") else: print("Key1 does not exist in the dictionary") # Check if "key4" is in the dictionary if "key4" in my_dict: print("Key4 exists in the dictionary") else: print("Key4 does not exist in the dictionary")
Key1 exists in the dictionary Key4 does not exist in the dictionary
To check if a given key exists in a dictionary in Python, you can use the in keyword. In this example, we create a dictionary called my_dict with three key-value pairs. Then, we use the in keyword to check if a given key exists in the dictionary. If the key exists, we print a message indicating that the key exists in the dictionary. Otherwise, we print a message indicating that the key does not exist in the dictionary.
Alternatively, you can use the dict.get() method to check if a given key exists in a dictionary. This method returns the value associated with the key if the key exists in the dictionary, or None if the key does not exist. Here is an example:
my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"} # Check if "key1" is in the dictionary if my_dict.get("key1") is not None: print("Key1 exists in the dictionary") else: print("Key1 does not exist in the dictionary") # Check if "key4" is in the dictionary if my_dict.get("key4") is not None: print("Key4 exists in the dictionary") else: print("Key4 does not exist in the dictionary")
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.