[Tutor] Concatenating Strings into Variable Names?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Feb 2 14:13:38 EST 2004


> This seems to be a very common question. Instead of using a 'regular'
> variable, you create a dictionary to hold your data. Then you use a
> string representing the variable's name as the key to that dictionary:
>
> myvars = {}
> myvars['choiceA_option1'] = 2.0
> myvars['choiceA_option2'] = 3.0
> myvars['choiceB_option1'] = 4.0
> myvars['choiceB_option2'] = 5.0
>
> choice=raw_input("Do you want choice A or B?")
> option=raw_input("Do you want option 1 or 2?")
>
> the_answer = "choice" + choice + "_option" + option
>
> if the_answer in myvars:
>     print 'answer:', myvars[the_answer]
> else:
>     print 'invalid choice/option combination'


Hi Steve,

I agree with Don; a "dictionary" seems like a good way to represent these
choices.  All of these choices are related, so using a single dictionary
container to hold them is probably a good idea to show that intent.


Here's a variation on Don's program:

###
all_choices = {}
all_choices['A', '1'] = 2.0
all_choices['A', '2'] = 3.0
all_choices['B', '1'] = 4.0
all_choices['B', '2'] = 5.0

choice = raw_input("Do you want choice A or B?")
option = raw_input("Do you want option 1 or 2?")

if (choice, option) in all_choices:
    print 'answer:', all_choices[choice, option]
else:
    print 'invalid choice/option combination'
###


Python's dictionaries are versatile, because not only can we use numbers
and strings as keys, but we're even allowed to use tuples!  The code above
does the same thing as Don's program, but instead of using strings as keys
into the dictionary, we use the (choice, option) pair.


Hope this helps!




More information about the Tutor mailing list