Reputation: 358
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.
Upvotes: 4
Views: 9427
Reputation: 611
We can check if the key 'key1' exists in the Json dictionary.
{
"key1":"value1"
}
To retrieve the value 'value1' if the key 'key1' exists in the dictionary.
if event.get('key1',None) != None:
value = event.get('key1',None)
Upvotes: -2
Reputation: 2524
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)
Upvotes: 26