to create variable from dict

Tim Chase python.list at tim.thechases.com
Fri Mar 12 09:40:52 EST 2010


hiral wrote:
> 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










More information about the Python-list mailing list