[Newbie] How to manipulate variable _names_ ?
Steve Holden
sholden at holdenweb.com
Fri Jun 28 09:28:21 EDT 2002
"Ben Fairbank" <baf at texas.net> wrote ...
> I have a program that requires the user to enter a file name, such as
> "othello," which the program will then open, process, and create a
> dictionary based on the contents of the file. I would like to name
> the dictionary "OthelloCount," and then go on and create more
> dictionaries, each with a name made up of the inputfile name as
> provided by the user, concatenated with "Count," but I do not know how
> to make a variable name based on input.
>
Ben:
Please note that it's almost always a bad idea to use data to generate
variable names this way. Why? Because you then end up having to execute
dynamically-constructed code to *use* those generated variables.
Python's dictionary mechanism is almost certainly what you want in this
case: if your file is called "myfile" then create an entry on some
dictionary (say Count["myfile"]) using the filename as a key. Then you don't
*need* to create variables on the fly. So your overall plan might look
something like this (untested):
Count = {}
for filename in "this", "that", "theother":
Count[filename] = AnalysisOf(file(filename).read())
This way will be easier, trust me.
regards
-----------------------------------------------------------------------
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------
More information about the Python-list
mailing list