site = object()
mydict = {'name': 'My Site', 'location': 'Zhengjiang'}
for key, value in mydict.iteritems():
setattr(site, key, value)
print site.a # it doesn't work
The above code didn't work. Any suggestion?
The easiest way to populate one dict with another is the update() method, so if you extend object to ensure your object has a __dict__ you could try something like this:
>>> class Site(object):
... pass
...
>>> site = Site()
>>> site.__dict__.update(dict)
>>> site.a
Or possibly even:
>>> class Site(object):
... def __init__(self,dict):
... self.__dict__.update(dict)
...
>>> site = Site(dict)
>>> site.a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With