1

Let's say I have a string like this.

string = "someString"

I now want to create a new instance of say, a dict() object using the variable stored in string. Can I do this?

string = dict()

Hoping it becomes "someString = dict()". Is this right? If not, how do i do it? Still learning python. Any help would be greatly appreciated.

user3078335
  • 781
  • 4
  • 13
  • 24
  • Can you show an example with expected output? – thefourtheye Feb 20 '14 at 01:36
  • you *almost certainly* shouldn't do this, but `globals()['someString'] = dict()` will do what you ask – mhlester Feb 20 '14 at 01:38
  • 1
    See [this question](http://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-in-python-via-a-while-loop) which includes many explanations of why you probably don't want to do this. – DSM Feb 20 '14 at 01:40

4 Answers4

2

Yes, it is possible to do this, though it is considered a bad thing to do:

string = 'someString'
globals()[string] = dict()

Instead you should do something like:

my_dynamic_vars = dict()
string = 'someString'

my_dynamic_vars.update({string: dict()})

then my_dynamic_vars[string] is a dict()

Douglas Denhartog
  • 2,036
  • 1
  • 16
  • 23
1

You really shouldn't do this, but if you really want to, you can use exec()

For your example, you would use this:

exec(string + " = dict()")

And this would assign a new dictionary to a variable by the name of whatever string is.

kabb
  • 2,474
  • 2
  • 17
  • 24
  • I don't recommend this, but I don't get the downvotes either. Unlike assignment to `locals()`, for example, this one will actually work. – DSM Feb 20 '14 at 01:46
  • I wouldn't recommend any kind of method that has variable variable names, but that's what OP is asking. Is there any particular reason why using locals() and globals() would be better than exec()? – kabb Feb 20 '14 at 01:49
1

Using black magic, the kind that send you to python hell, it's possible.

The globals() and locals() functions, for example, will give you the dictionaries that contain variables currently in scope as (key, value) entries. While you can try to edit these dictionaries, the results are sometimes unpredictable, sometimes incorrect, and always undesirable.

So no. There is no way of creating a variable with a non-explicit name.

salezica
  • 74,081
  • 25
  • 105
  • 166
1

If the variable you want to set is inside an object, you can use setattr(instance,'variable_name',value)

XrXr
  • 2,027
  • 1
  • 14
  • 20