Handling KeyError

# Define a dictionary
my_dict = {"name": "Alice", "age": 25}

# Try to access a non-existent key
try:
    print(my_dict["gender"])
except KeyError as e:
    print(f"KeyError: {e}")
KeyError: 'gender'
# Define a dictionary
my_dict = {"name": "Bob", "age": 30}

# Check if the key exists before accessing it
if "gender" in my_dict:
    print(my_dict["gender"])
else:
    print("Key 'gender' not found")
Key 'gender' not found
# Define a dictionary
my_dict = {"name": "Charlie", "age": 35}

# Use the get method to safely access the key
gender = my_dict.get("gender", "Not specified")
print(gender)
Not specified
# Define a dictionary
my_dict = {"name": "Diana", "age": 40}

# Use setdefault to set a default value if the key does not exist
gender = my_dict.setdefault("gender", "Not specified")
print(gender)
print(my_dict)  # Output: {'name': 'Diana', 'age': 40, 'gender': 'Not specified'}
Not specified
{'name': 'Diana', 'age': 40, 'gender': 'Not specified'}
from collections import defaultdict

# Define a defaultdict with a default value of 'Not specified'
my_dict = defaultdict(lambda: "Not specified")
my_dict["name"] = "Eve"
my_dict["age"] = 45

# Access a non-existent key
print(my_dict["gender"])  # Output: Not specified
Not specified
# Define a dictionary
my_dict = {"name": "Frank", "age": 50}

# Try to access a non-existent key and handle the KeyError
try:
    print(my_dict["gender"])
except KeyError:
    print("Key 'gender' not found")
    # You can also set a default value or take other actions
    my_dict["gender"] = "Not specified"
    print(my_dict["gender"])
Key 'gender' not found
Not specified