[Tutor] creating variables from the 'key' of a dictionary.

Jeff Shannon jeff at ccvcorp.com
Fri Jul 2 15:13:22 EDT 2004

Larry Blair wrote:

> I think what I want to do is create a function that would load a dictionary
> with all parameters from the file. 
> Then in the original script use that dictionary in a for loop to create the
> variables from the key.
> My question is there a way to create a variable with the name of the key in
> a dictionary i.e.
> para = {}
> para['source_server'] = 'cm05'

Yes, you can do that.  The following three code fragments all result 
in an identical dictionary:

     para = { 'source_server':'cm05' }

     para = {}
     para['source_server'] = 'cm05'

     key = 'source_server'
     value = 'cm05'
     para = {}
     para[key] = value

In addition, there's a couple of things that might make your life even 

First, consider creating a Python module called settings.py, which 
contains the definition of your parameters dictionary:

----- settings.py ---------

para = { 'source_server':'cm05',
           ...                    }

Now, in your other files, you can simply

import settings

src = settings.para['source_server']

Second, if your settings are very dynamic and change often, it might 
be useful to investigate the shelve module.  This is a library module 
that will essentially allow you to store the current state of a 
dictionary as a disk file, and to later reload that dictionary from 
the file.  This would let you have a persistent record of the most 
recent state of your parameters.

Jeff Shannon
Credit International

More information about the Tutor mailing list