Setting variable values from dictionary
Robert Brewer
fumanchu at amor.org
Fri Apr 23 11:22:57 EDT 2004
Sean Berry wrote:
> If I have a dictionary like the following:
>
> {'category' : 2, 'shape', 4}
>
> How can I use this to make
> category = 2 and
> shape = 4.
>
> I want to be able to do this regardless of the dict values type. So:
>
> {'cateogry' : 2, 'shape' : 'circle'}
>
> will work as well.
Others will probably show you how to do this, but in most cases, I've
been better off making attributes of a new object instead of
module-level globals.
>>> attrs = {'category' : 2, 'shape' : 'circle'}
>>> class Namespace(object): pass
...
>>> ns = Namespace()
>>> ns.__dict__.update(attrs)
>>> ns.shape
'circle'
...that way, you "cordon off" all of your shiny new dynamic 'variables'
into their own namespace.
Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org
More information about the Python-list
mailing list