Setting variable values from dictionary

Dave Kuhlman dkuhlman at rexx.com
Fri Apr 23 12:13:00 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.

    locals().update(mydict)

Oops.  I just actually read the docs:

    locals(     )
        Update and return a dictionary representing the current 
        local symbol table. *Warning*: The contents of this
        dictionary should not be modified; changes may not affect
        the values of local variables used by the interpreter.

[Emphasis added.]

So, perhaps, the following is to be preferred:

    for name, value in mydict.items():
        exec('%s = %s' % (name, value))

But, what do you want to do about name clashes?

Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman



More information about the Python-list mailing list