Function 'hasattr()' doesn't work as I expected in Python

3.8k Views Asked by At

Function 'hasattr()' doesn't work as I expected in Python

I have the following code:

#!/usr/bin/python
import re
import os
import sys

results=[{'data': {}, 'name': 'site1'}, {'data': {u'Brazil': '5/1', u'Panama': '2000/1'}, 'name': 'site2'}]

print results[1]
if hasattr(results[1]['data'], u'Brazil'):
    print 'has'
else:
    print 'hasn\'t'

When I run it, it gives me the output: hasn't.
I don't understand how to check the property if it exists.
I tried to remove u before Brazil but it doesn't work.
How to solve it?

2

There are 2 best solutions below

0
willeM_ Van Onsem On BEST ANSWER

hasattr(..) checks if an object has an attribute with the given name. But like the conditions says correctly, there is no somedict.Brazil.

You can check membership of a key in a dictionary with in, like:

if u'Brazil' in results[1]['data']:
    print 'has'
else:
    print 'hasn\'t'

Note that this only checks if there is a key in the dictionary that is equal to the given key (u'Brazil'), it does not check the values, for values, you can for instance use '5/1' in results[1]['data'].values(). Note that searching for keys is usually done in O(1), whereas searching for values will run in O(n).

0
ACascarino On

hasattr operates on attributes, not on dictionary keys - if you can access it with dot notation (as in data.Brazil) then hasattr will return True, otherwise it will return False- and in this case it will return False.

Use in instead:

if u'Brazil' in results[1]['data']: