【问题标题】:if statement not working in AWS lambda consoleif 语句在 AWS lambda 控制台中不起作用
【发布时间】:2021-08-15 08:14:28
【问题描述】:

我正在尝试在 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' 键,我希望它会打印 'goodbye'。但是,我收到以下错误:

[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”吗?任何帮助表示赞赏,谢谢。

【问题讨论】:

  • 如您所见,test_dict 中有“x”。所以请先检查它是否有“x”if "x" in test_dict:

标签: python json function if-statement aws-lambda


【解决方案1】:

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

if 'x' in test_dict.keys()

elif test_dict['y']相同

【讨论】:

    猜你喜欢
    • 2017-01-17
    • 2017-05-22
    • 2017-03-19
    • 1970-01-01
    • 2021-01-28
    • 2012-07-16
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多