1

I am somewhat new to Python - after searching I cannot find an answer to this 'simple' question.

I am defining several custom data structures, and need each one to be named after the value contained in a variable. I am sure the answer is very simple - code shows an example of what I am trying to achieve.

 class aDataStructure:
     def __init__(self, value):
          self.value=value

 String1 = "name"

 # How to define this data structure with the String contained in 'String1'?
 ??? = aDataStructure ('a value')

 print name.value
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
JBiss
  • 131
  • 10
  • Why do you want to name a data structure by the *value*? –  Feb 12 '15 at 15:07
  • 4
    possible duplicate of [How do I do variable variables in Python?](http://stackoverflow.com/questions/1373164/how-do-i-do-variable-variables-in-python) – jonrsharpe Feb 12 '15 at 15:08

1 Answers1

0

As mentioned in this answer, if you need to use variable variables, a good implementation is to use a dictionary, which maps the variable tied to the name onto the data structure you're creating:

>>> string1 = "name"
>>> dict = {string1 : aDataStructure('a value')}
>>> dict["name"]
<__main__.aDataStructure instance at 0x10ce1db48>
Community
  • 1
  • 1
seanmhanson
  • 219
  • 1
  • 6