Bird
0
0

You wrote this AWS Lambda function in Python:

medium📝 Debug Q14 of 15
AWS - Lambda
You wrote this AWS Lambda function in Python:
def handler(event, context):
    return event['message']

When triggered with event {}, it throws a KeyError. How can you fix it?
AUse event.get('message', 'No message') instead of event['message']
BRemove the return statement
CAdd a print statement before return
DChange function name to lambda_handler
Step-by-Step Solution
Solution:
  1. Step 1: Identify cause of KeyError

    Accessing event['message'] when 'message' key is missing causes KeyError.
  2. Step 2: Use safe access method

    Replacing event['message'] with event.get('message', 'No message') avoids error by providing default.
  3. Final Answer:

    Use event.get('message', 'No message') instead of event['message'] -> Option A
  4. Quick Check:

    Use get() to avoid KeyError on missing keys [OK]
Quick Trick: Use get() with default to prevent KeyError [OK]
Common Mistakes:
  • Ignoring missing key causes error
  • Thinking print fixes KeyError
  • Assuming function name affects key access

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More AWS Quizzes