[Tutor] Using a string to get at a Variable

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Jan 19 02:16:04 EST 2004

> I don't understand the code you wrote, and what exactly its supposed to
> do. But this is what I'm looking for.
> apples = 10
> grapes = 5
> pears = 8
> fruits = ['apples', 'grapes', 'pears']
> Now Iswant to be able to do something like this.
> for fruit in fruits:
> 	print 'You heve %d' % (fruit), fruit
> And the output should look like this:
> You have 10 apples
> You have 5 grapes
> You have 8 pears
> Thanks for the reply and if anyone can help it would be appreciated.

Hi Isr,

You may want to look at dictionaries:


And by "may", I emphatically mean "You really should look at
dictionaries."  *grin*

Instead of using the separate variables 'apples', 'grapes', and 'pears',
we can use a dictionary to collect them all together:

>>> fruitbasket = {}
>>> fruitbasket['apples'] = 10
>>> fruitbasket['grapes'] = 5
>>> fruitbasket['pears'] = 8

We can take a look at the fruitbasket as a whole:

>>> fruitbasket
{'pears': 8, 'apples': 10, 'grapes': 5}

or just pick individual fruits out by name:

>>> fruitbasket['pears']
>>> fruitbasket['grapes']

Play around with dictionaries more, and you should see how to use them to
make your program run well.

The solution with eval() that you found does work, but it is, well...
truthfully speaking, very nonstandard...  *grin*  Dictionaries are a
concept in almost all programming languages, whereas eval() is not so
widespread.  You'll get better mileage out of understanding dictionaries.

Good luck to you!

More information about the Tutor mailing list