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?
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).