Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS Lambda Python 3 check event variable exists

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

This is throwing a 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.

like image 857
Stephen Lester Avatar asked Oct 20 '25 21:10

Stephen Lester


1 Answers

Use the get method. 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)
like image 80
mypetlion Avatar answered Oct 22 '25 11:10

mypetlion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!