0

I want to automatically define variables using a dynamic string, similar to ${$a} in PHP.

As I do this in a plain script I do not have objects and therefore can not apply setattr or am I wrong?

How do I dynamically define variables?

Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
lony
  • 6,733
  • 11
  • 60
  • 92

2 Answers2

0

You can store the variables you want in a dictionary. That's basically what php does, only in Python you can specify which dictionary to use and how to handle it.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
-1

You can modify local or global dictionary:

>>> locals()['xxx'] = 'Hi'
>>> xxx
'Hi'
>>> globals()['yyy'] = 'Hello'
>>> yyy
'Hello'
pbacterio
  • 1,094
  • 6
  • 12