Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: convert string into variable name [duplicate]

Tags:

python

here is my python code:

>>> listName = 'abc'
>>> exec(listName+"=[]")
>>> print listName
>>> 'abc'

excepted output:

>>> print listName
>>> []

I want to define a new variable based on that string.

like image 416
NIKHIL RANE Avatar asked Aug 23 '26 00:08

NIKHIL RANE


1 Answers

Even though that may be possible for global (and not local) variables, the better, cleaner, simpler, safer, saner (all in one word: pythonic) way is to use a dictionary for dynamic names:

values = {}
varname = get_dynamic_name()
# set
values[varname] = value
# get
values[varname]
like image 183
bereal Avatar answered Aug 24 '26 12:08

bereal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!