AttributeError: 'NoneType' object has no attribute 'get' despite dictionary being full

Viewed 21

I'm using Perspective API to get toxicity scores from Twitter data. However, I get this error even though my dictionary isn't empty AttributeError: 'NoneType' object has no attribute 'get':

def getToxicityScores(sentence): 

analyze_request = {
    'comment': {
        'text': sentence },
    'requestedAttributes': {
        'TOXICITY': {}, 
        'INSULT': {}, 
        'IDENTITY_ATTACK': {}, 
        'THREAT': {}
    }
}

response = client.comments().analyze(body=analyze_request).execute()
#print(response.get('attributeScores', {}))
print(response.keys())

perspect_dict = {
    'Profanity': response.get('attributeScores', {}).get('PROFANITY').get('spanScores')[0].get('score').get('value'), 
    'Toxicity': response.get('attributeScores', {}).get('TOXICITY').get('spanScores')[0].get('score').get('value'), 
    'Threat': response.get('attributeScores', {}).get('THREAT').get('spanScores')[0].get('score').get('value'), 
    'IdentityAttack': response.get('attributeScores', {}).get('IDENTITY_ATTACK').get('spanScores')[0].get('score').get('value'), 
    'Insult': response.get('attributeScores', {}).get('INSULT').get('spanScores')[0].get('score').get('value')
}

time.sleep(40)

return perspect_dict

My call: getToxicityScores('shut up')strong text

1 Answers

You need to add appropriate default values to all the .get() calls. If there's no attributeScores key in the response dictionary, you return an empty dictionary from the first .get(), and then all the following .get() calls will return None by default. This will then get an error when you try to call .get('spanScores').

And you need to give .get('spanScores') a default that allows [0].get('score') to work. And so on.

perspect_dict = {
    'Profanity': response.get('attributeScores', {}).get('PROFANITY', {}).get('spanScores', [{}])[0].get('score', {}).get('value', 0), 
    'Toxicity': response.get('attributeScores', {}).get('TOXICITY', {}).get('spanScores', [{}])[0].get('score', {}).get('value', 0), 
    'Threat': response.get('attributeScores', {}).get('THREAT, {}').get('spanScores', [{}])[0].get('score', {}).get('value', 0), 
    'IdentityAttack': response.get('attributeScores', {}).get('IDENTITY_ATTACK', {}).get('spanScores', [{}])[0].get('score', {}).get('value', 0), 
    'Insult': response.get('attributeScores', {}, [{}]).get('INSULT', {}).get('spanScores')[0].get('score', {}).get('value', 0)
}

This would be easier if you put that chain of .get calls into a function, so you could just call it repeatedly instead of repeating all this code.

Related