3
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?

1
  • it would be helpful when you say something doesn't work, to give a bit more information like what you wanted to happen, and/or any exceptions thrown, etc. Commented Oct 7, 2010 at 14:25

3 Answers 3

7

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 
Sign up to request clarification or add additional context in comments.

Comments

5

As docs say, object() returns featureless object, meaning it cannot have any attributes. It doesn't have __dict__.

What you could do is the following:

>>> site = type('A', (object,), {'a': 42}) >>> site.a 42 

Comments

1
class site(object): pass for k,v in dict.iteritems(): setattr(site,k,v) print site.a #it does works 

3 Comments

'object' object has no attribute 'dict'
your solution may end up being more confusing to the original poster. In their original code, they want to add attributes to an object which is an instance of object. However, you offer a solution which adds attributes to the class site. I recognize that it works, but may not be what they had in mind.
accepted solution does the same, as adding an attribute to an object instance is not possible

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.