-1

So i have code like this

varName = 'test'
varContents = 'something'

My question is:
How do i create a variable with the name of the contents of varName, having contents containing the contents of varContents?

Connor Club
  • 64
  • 1
  • 7
  • 1
    Why do you want to create a variable dynamiclly ? How to you plan to use it after ? In generak that **is not** to create variable name dynamically, because the variable name represent nothing in fact – azro Nov 06 '20 at 18:19
  • 1
    Does this answer your question? [Why shouldn't one dynamically generate variable names in python?](https://stackoverflow.com/questions/50583955/why-shouldnt-one-dynamically-generate-variable-names-in-python) – Samwise Nov 06 '20 at 18:23

2 Answers2

0

Generally you'll want to avoid doing this - especially if you are dealing with user inputs, but you can use the exec() function. It runs a string passed into it as code, so you can do something like:

varName = 'test'
varContents = 'something'
exec(f"{varName} = '{varContents}'")
print(test)

A better way of storing data with a dynamic key is with a dict like this:

myDict = {}
varName = 'test'
varContents = 'something'

myDict[varName] = varContents
print(myDict[varName])
Alexanderbira
  • 434
  • 3
  • 14
-1

you can create variables like this :

locals()['newVar'] = "local variable"
print (newVar)

globals()['newGlobalVar'] = "global variable"
print (newGlobalVar)

so you could do this :

locals()[varName] = varContents
# Or
globals()[varName] = varContents
dspr
  • 2,383
  • 2
  • 15
  • 19