mercredi 26 mai 2021

if statement not working in AWS lambda console

I am trying to use a simple if statement (python) in AWS lambda console. I have a dictionary, and would like to do different things based on whether there are specific keys in the dictionary. The code is quite long, but in summary it is as follows:

def myFunction(test_dict):
    test_dict = json.loads(test_dict) # test_dict is a str, so I am loading it as a json object

    if test_dict['x']:
         print('hello')
    elif test_dict['y']:
         print('goodbye')
    else:
         print('No property is printed')

If test_dict only has the 'y' key, I am expecting it to print 'goodbye'. However, I get the following error:

[ERROR] KeyError: 'x'
Traceback (most recent call last):
   File "/var/task/index.py", line 140, in lambda_handler
        myFunction(test_dict)
   File "var/task/index.py", line 14, in myFunction
        if test_dict['x']

Why is the if statement stopping when it detects there is no 'x' key in test_dict? Does it not go on to evaluate whether 'y' is present in test_dict? Any help is appreciated, thanks.

Aucun commentaire:

Enregistrer un commentaire