Skip to content
Advertisement

Error handling in variables when using Requests

I have the below code that works fully up until I set x=37. At this point, I receive the error

TypeError: ‘NoneType’ object is not subscriptable on the variable t[“vintage”][“wine”][“region”][“country”][“name”].

I have added another variable that the same issue happens on almost everytime, so you may find the error there instead.

I think this is because one of the 25 results on that page does not have a country name assigned to it and therefore the variable is giving an error.

I think I need to add an exception to each variable to handle where this is the case. I have seen examples of adding these except, they seem to be at the level of the request not finding a legitimate page rather than one of the variables and I can’t find guidance to add them at the variable level.

JavaScript

Advertisement

Answer

The problem is that some keys are randomly missing (notated with None) in a deeply nested dictionary. A sample dictionary demonstrating the struggle:

JavaScript

When you assume the key k3 certainly exists in each dictionary in an array, it does not. Hence when you try to do something like

JavaScript

You get TypeError: 'NoneType' object is not subscriptable.

TypeError arises when t['k1']['k2'] evaluates to None in the second iteration under the for-loop, and you attempt to look for a key in it. You are basically asking the program to execute None['k3'], which explains the error message you’ve got.

To sovle this issue (which is very common in returned data from API requests), you will need to try-catch the block. You may find this helper function useful:

JavaScript

Using the helper function, we can write try_to_get(t, 'k1, 'k2', 'k3). While a non-problematic dictionary would traverse down the nests and get the value you want, a problematic one will trigger the Exception block and return a deafult value when there is an error (here, the default value is None).

You can try to replace the list comprehension part in your code with this:

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