[Tutor] Assigning a variable stored in a dictionary

Kent Johnson kent37 at tds.net
Thu Jan 4 21:54:11 CET 2007

Tony Cappellini wrote:
> I can't see the forest through the trees.
> I have stored 3 global variables in a dictionary, and associated each 
> variable with a filename.
> Ideally, I want to read the contents of the text files, and store the 
> contents in the global variables. The globals will be used by another 
> function.
> However, when I do the assignment to varname = fh.readlines(), a new 
> variable is created, and the reference to the global variable is 
> overwritten, because the contents of the files are strings, and strings 
> are immutable.
> I see the problem, but not a good solution.
> var1=""
> var2=""
> var3=""
> def initGlobals():
>     global var1, var2, var3
>     fileDict = {'var1.txt ':var1, 'var2.txt':var2, 'var3.txt':var3}
>     for fn, varname in fileDict.iteritems():
>         try:
>             try:
>                 fh=open(fn, 'r')
>                 #id(varname) # at this point, this id matches the id of 
> the global variable
>                 varname = fh.readlines() # this creates a new variable, 
> but I want to store the file contents in the global var
>                 #id(varname)                  # this is a new id, the 
> global var is not updated
>                 fh.close()
>             except IOError:
>                 print "\nFATAL ERROR occurred reading %s\n" % fn
>         finally:
>             fh.close()

You have a fundamental misunderstanding of the nature of variables and 
names in Python. This may help:

Python variables are *not* containers for values, they are references to 
values. They are names for values. Some people like to think of a Python 
name as a sticky note that gets put on the value, giving it a name. I 
like to think of a name as pointing to a value.

The values of your fileDict are just references to the empty string, 
they don't have any association at all with the global variables you 
want to change; they just happen to have the same value.

The easiest solution is to just use the dict to store the file names and 
data, forget about the global variables:

fileData = {}
for name in 'var1.txt', 'var2.txt', 'var3.txt':
	f = open(name)
	fileData[name] = f.readlines()

At this point you have a dict whose keys are the three file names and 
whose associated values are the contents of the files.


More information about the Tutor mailing list