Skip to content
Advertisement

Python: when trying to extract certain keys, how can I avoid a KeyError when in some dict elements, the key value is missing from APi json?

I can successfully extract every column using Python, except the one I need most (order_id) from an API generated json that lists field reps interactions with clients.

Not all interactions result in orders; there are multiple types of interactions. I know I will need to add the flag to show ‘None’ and then in my for loop and an if-statement to check whether the order_id is null or not. If not ‘None/null’, add it to the list.

I just cannot figure it out so would appreciate every bit of help!

This is the code that works:

JavaScript

This returns an error-free result:

JavaScript

When I include the order_id in the loop:

JavaScript

It returns:

JavaScript

Advertisement

Answer

Use the get method of the dictionary:

JavaScript

This will set your missing values to None. If you want to choose what the None value is, pass a second argument to get e.g. item.get('user_name', 'N/A')

EDIT: To conditionally add items based on the presence of the order_id

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement