I have tried at learnpython.org to create a variable dynamically it can be create as below :
food = 'bread'
vars()[food] = 'asdasd'
print (bread)
It will print out "asdasd". However when I tried with my python3, it gives me an error (NameError: name 'bread' is not defined). How can I do that using python3?
martineau
124k29 gold badges181 silver badges319 bronze badges
asked Feb 1, 2018 at 16:36
Django newbie
1231 gold badge3 silver badges12 bronze badges
-
9This can be done, but it is a terrible anti-pattern. If you have to do this, usually something is very wrong with the design.willeM_ Van Onsem– willeM_ Van Onsem2018年02月01日 16:38:09 +00:00Commented Feb 1, 2018 at 16:38
-
2I cannot reproduce this. It works fine for me.internet_user– internet_user2018年02月01日 16:38:52 +00:00Commented Feb 1, 2018 at 16:38
-
1@StefanPochmann I think the OP is saying that he was using the websites built-in Python IDE to run his code.Chris– Chris2018年02月01日 16:41:09 +00:00Commented Feb 1, 2018 at 16:41
1 Answer 1
In python we tend to avoid this kind of dynamic variables, but anyway your answer is:
a = 'test'
globals()[a] = 123
print(test)
Better approach is by using a dictionnary.
a = 'test'
myVar = {}
myVar[a] = 123
print(myVar['test'])
Sign up to request clarification or add additional context in comments.
4 Comments
Django newbie
currently, my issue is I need to read a csv file and based on the user selected columns, I need to create a var to store it. if i ignore this kind of dynamic variables, is there any other way to do it?
scholi
The way to do it is to store it in a dictionnary or a list and access it via a key.
Django newbie
It doesn't work. what I need is i have a variable temp1, storing a value, temp1 = "country" i wanted to used that country as a variable for another variable, for example: country = "UK"
juanpa.arrivillaga
@Djangonewbie just use a
dictlang-py