user3078335
user3078335

Reputation: 781

Usng the value of a string as a variable name

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.

Upvotes: 1

Views: 89

Answers (4)

XrXr
XrXr

Reputation: 2057

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

Upvotes: 1

salezica
salezica

Reputation: 76899

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.

Upvotes: 1

Douglas Denhartog
Douglas Denhartog

Reputation: 2054

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()

Upvotes: 2

kabb
kabb

Reputation: 2502

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.

Upvotes: 1

Related Questions