to create variable from dict

H

hiral

Hi,

Is there any way to create variables which name matches with dict key?

For example:
dict1 = {"abc":'1", "def":"2"}

Now I am looking to have variable name abc and it's value be '1' etc.

Pl. suggest.

Thank you.
 
T

Tim Chase

hiral said:
Is there any way to create variables which name matches with dict key?

For example:
dict1 = {"abc":'1", "def":"2"}

Now I am looking to have variable name abc and it's value be '1' etc.

1) you can't because "def" is a reserved word in Python.

2) why do you want to? This seems to come up about every week or
so and people STILL want to do it. Search the archives...you
won't have to go back too far.

3) once you have it, how do you plan to use the variables? If
you don't know what they'll be named ahead of time, how can you
use them in your code

The usual answer is "don't do that -- just use them as a dict",
or if you're trying to set up some constants, you can use

abc, def_, ghi = 1, 2, 3

-tkc
 
L

Luis M. González

Hi,

Is there any way to create variables which name matches with dict key?

For example:
dict1 = {"abc":'1", "def":"2"}

Now I am looking to have variable name abc and it's value be '1' etc.

Pl. suggest.

Thank you.

Check out this thread (very recent):
http://groups.google.com/group/comp...31f?lnk=gst&q=luis+variables#25fe94103c7a231f

Short answer: you can update globals() with a dictionary, as follows:

globals().update( dict1 )

Then you'll have each key-value pair as variables in the global
namespace.
The question is: should you do it?

Luis
 
A

Andreas Waldenburger

The question is: should you do it?

And the answer is: No.

And the usual disclaimer is: (Unless you *know* it's the best possible
solution to your problem.)

/W
 

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
474,176
Messages
2,570,949
Members
47,500
Latest member
ArianneJsb

Latest Threads

Top