4
 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.

2 Answers 2

26

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)
Sign up to request clarification or add additional context in comments.

1 Comment

For certain data... such as OrderItems in Amazons SP-API, you can't apply the 'data.get()` function for keys because it's a list of dictionaries. Getting main_data = res.get_order_items() initial payload, then using ord_items = main_data.get('OrderItems') to get correct data... but trying to use ord_items.get('ASIN','') does not work "list has no attribute get()". Is there a way around this? As this is the easiest way to check if a key exists. I've been having to use main_data['OrderItems'][0]['ASIN'].
-2

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)

1 Comment

Technically it does, but it's not the most elegant solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.