【发布时间】: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