简体   繁体   English

AWS Lambda Python 3 检查事件变量是否存在

[英]AWS Lambda Python 3 check event variable exists

 try: 
        event['ids']
 except NameError: 
        ids = None

This is throwing a KeyError.这是抛出一个 KeyError。 I just want to check if the event variable exists and set to none or pass the value if it does.我只想检查事件变量是否存在并设置为无,如果存在则传递该值。 I have also tried to use我也尝试过使用

if (len(event['ids']) < 1) 

but get an error.但得到一个错误。 Am I missing something?我错过了什么吗? I may or may not have all my event keys passed and want to check for existence.我可能会也可能不会传递我所有的事件密钥,并想检查是否存在。

Use the get method. 使用get方法。 The second parameter is the default value if the key doesn't exist in the dictionary. 如果字典中不存在键,则第二个参数是默认值。 It's the standard way to get values from a dictionary when you're not sure if the key exists and you don't want an exception. 当您不确定键是否存在并且您不希望发生异常时,这是从字典中获取值的标准方法。

ids = event.get('ids', None)

We can check if the key 'key1' exists in the Json dictionary.我们可以检查 Json 字典中是否存在键 'key1'。

{ 
"key1":"value1"
}

To retrieve the value 'value1' if the key 'key1' exists in the dictionary.如果字典中存在键“key1”,则检索值“value1”。

if event.get('key1',None) != None:
   value = event.get('key1',None)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM