In Python, dictionaries are powerful data structures for storing key-value pairs. In this blog post, we will explore how to check if a key exists in a dictionary using different methods.
Method 1: Using the ‘in’ Keyword
# Method 1: Using the 'in' Keyword my_dict = {"name": "John", "age": 30, "city": "New York"} if "age" in my_dict: print("Key 'age' exists in the dictionary.")
Output:
Key ‘age’ exists in the dictionary.
Method 2: Using the get() Method
# Method 2: Using the get() Method my_dict = {"name": "John", "age": 30, "city": "New York"} if my_dict.get("age") is not None: print("Key 'age' exists in the dictionary.")
Output:
Key ‘age’ exists in the dictionary.