首页 > 解决方案 > if 语句在 AWS lambda 控制台中不起作用

问题描述

我正在尝试在 AWS lambda 控制台中使用一个简单的 if 语句(python)。我有一本字典,并且想根据字典中是否有特定的键来做不同的事情。代码很长,但总结如下:

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')

如果 test_dict 只有“y”键,我希望它打印“再见”。但是,我收到以下错误:

[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']

为什么if语句在检测到test_dict中没有'x'键时停止?它不会继续评估 test_dict 中是否存在“y”吗?任何帮助表示赞赏,谢谢。

标签: pythonjsonfunctionif-statementaws-lambda

解决方案


如果您test_dict的键中没有“x”,那么您将收到错误消息。您应该使用: if 'x' in test_dict而不是if test_dict['x'] 或:

if 'x' in test_dict.keys()

elif test_dict['y']


推荐阅读