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")
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.
Subscribe to be the first to know when a new Python course is released.