[Newbie] How to manipulate variable _names_ ?

Emile van Sebille emile at fenx.com
Thu Jun 27 15:41:22 CEST 2002


Ben Fairbank
> 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.
>

One way is to use getattr:

import sys

def orderspam(): return 'Hmm, spam?'
def ordereggs(): return 'Hmm, eggs?'
for ii in ('spam','eggs'):
    print getattr(sys.modules[__name__], 'order%s' % ii)()


Or, you could create a single dictionary, counts, with keys like othello
and values being the results of your processing.

HTH,

--

Emile van Sebille
emile at fenx.com

---------




More information about the Python-list mailing list