1

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
3
  • 9
    This can be done, but it is a terrible anti-pattern. If you have to do this, usually something is very wrong with the design. Commented Feb 1, 2018 at 16:38
  • 2
    I cannot reproduce this. It works fine for me. Commented 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. Commented Feb 1, 2018 at 16:41

1 Answer 1

4

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'])
answered Feb 1, 2018 at 16:39
Sign up to request clarification or add additional context in comments.

4 Comments

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?
The way to do it is to store it in a dictionnary or a list and access it via a key.
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"
@Djangonewbie just use a dict

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.