python - 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”吗?任何帮助表示赞赏,谢谢。
解决方案
如果您test_dict
的键中没有“x”,那么您将收到错误消息。您应该使用:
if 'x' in test_dict
而不是if test_dict['x']
或:
if 'x' in test_dict.keys()
与elif test_dict['y']
推荐阅读
- scrapy - 如何在scrapy中解析两个不同的项目?
- javascript - Javascript匹配函数在for循环中不起作用
- javascript - React APP上指定了img路径也没有响应
- android-studio - 无法启动安卓模拟器。它没有给我指定的avd
- r - 多个数据帧上的一组函数并合并 R 中的输出
- python-3.x - 使用 selenium 时禁用 Safari 中的自动化警告
- java - 这个循环执行多少次迭代?
- javascript - 将值一一插入到搜索字段中,同时用相同的按钮一一显示图像?
- html - 如何更改页面的资源 URL?
- mysql - Mysql Select 记录 '23:57:58' 和 '00:07:58' 之间的时间