Setting variable values from dictionary

S

Sean Berry

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.


Thanks in advance for any help. You guys rock.

--
 
D

Dave Kuhlman

Sean said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top