Can I get a variable with a variable? Like php.

This is a simple question.


sally = 25
jenny = 27

name = 'sally'

Is there a way for me to get the value of sally using the variable name?

I know it can be done in php.

#php code

<?php

$sally = 25;
$jenny = 27;
$name = 'sally';

echo $$name;
?>

this would do the trick:


print eval(name)

It wouldn’t be particularly efficient though. Depending on what you need you might be better of with maintaining a dictionary of names:


vars={}
vars['jenny']=21
vars['sally']=22
name='sally'
print vars[name]

depending on the scope of your defined variables this might work as well:


print locals()[name]

locals() might be replaced by globals() depending on the scope.