Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   converting dict to object (http://www.velocityreviews.com/forums/t396929-converting-dict-to-object.html)

rieh25 12-02-2006 01:48 AM

converting dict to object
 

If I have a dictionary such as:

d = {'a' : 1, 'b' : 2}

is there a way to convert it into an object o, such as:

o.a = 1
o.b = 2

thanks
--
View this message in context: http://www.nabble.com/converting-dic....html#a7649225
Sent from the Python - python-list mailing list archive at Nabble.com.


Carl D. Roth 12-02-2006 05:56 PM

Re: converting dict to object
 
On Fri, 01 Dec 2006 17:48:40 -0800, rieh25 wrote:

> If I have a dictionary such as:
>
> d = {'a' : 1, 'b' : 2}
>
> is there a way to convert it into an object o, such as:
>
> o.a = 1
> o.b = 2


Rather, the question could be asked the other way around: how can you
convert that object into a dict?

The attributes in 'o' are part of its '__dict__' attribute, which is a
dictionary. That is,

o.a = 1

is equivalent to

o.__dict__['a'] = 1

If you already have a dictionary 'd', you can overlay it onto the object's
attributes with

o.__dict__.update(d)

Carl


All times are GMT. The time now is 04:48 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.