from dict to member vars...?

Jeremy Jones zanesdad at bellsouth.net
Thu Oct 14 14:19:43 EDT 2004


Diez B. Roggisch wrote:

>Christopher J. Bottaro wrote:
>
>  
>
>>Hello,
>>
>>Lets say I have a class instance with the following member vars:  var1, x,
>>size.  Now lets say I have dict with the following keys:  var1, x, size.
>>Is there an easy way to *automatically* assign all the values in the dict
>>to corresponding (member) vars of the same name as the dict keys?
>>    
>>
>
>d = dict(...)
>
>for key, val in d.items():
>   setattr(o, key, val)
>
>  
>
Why not just use update()?

In [11]: class TestClass:
   ....:     def __init__(self):
   ....:         self.var1 = 0
   ....:         self.x = 0
   ....:         self.size = 0
   ....:

In [12]: tc = TestClass()

In [13]: tc.__dict__
Out[13]: {'x': 0, 'var1': 0, 'size': 0}

In [14]: tc.__dict__.update({'x': 'this is x', 'var1': 'this is var1', 
'size': 125})

In [15]: tc.var1
Out[15]: 'this is var1'

In [16]: tc.x
Out[16]: 'this is x'

In [17]: tc.size
Out[17]: 125

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20041014/4225d835/attachment.html>


More information about the Python-list mailing list