1

How can I convert string values into python variables?

The setup is the following: I have variable_names = ['a', 'b', 'c'] and I would like to create for each item in variable_name a variable which I can assign a value to (like this a = 10, b = 20, c = 30). I do not want a dictionary. When I print(a) I should get 10.

5
  • 2
    Better use a dictionary Commented Oct 13, 2021 at 10:12
  • 2
    Short answer, don't do this. Longer answer seriously, don't do this, you'll run into issues, you can do without it, your code would be messy Commented Oct 13, 2021 at 10:15
  • You got a notification with links to duplicates while you were writing this question. Commented Oct 13, 2021 at 10:18
  • That does unfortunately not answer my question. I later need to process the input in the following way: a = sp.Symbol('a') using the sympy library. This is why a needs to be a stand alone variable. Commented Oct 13, 2021 at 10:20
  • 2
    @Mariusmarten - That would have been a better question than your very general question, which already has multiple answers on stackoverflow. Does this help? How can I dynamically generate a python symbol statement? Commented Oct 13, 2021 at 10:25

3 Answers 3

3

I just cobbled a quick example to do what you want to do, I do not recommend that you do this, but I will assume that you have a good reason to and will therefore help.

vars = ["a", "b", "c"]
for i in range(len(vars)):
   globals()[vars[i]] = (i+1)*10

print(a) # 10
print(b) # 20
print(c) # 30

This example may be a little complicated but it does exactly what you asked for in your question, long story short you can use the globals() function to turn a string into a variable. Link for more info here: https://www.pythonpool.com/python-string-to-variable-name/

Sign up to request clarification or add additional context in comments.

Comments

3

Built-in function globals() give you access to all variable in our code. So, with that you can convert each of your string to variable, like

globals()['a'] = 5
print(a) # 5

So, you need just to iterate through list and assign each variable to desired value.

values = [10, 20, 30]
for i in range(len(variable_names)):
    globals()[variable_names[i]] = values[i]

Comments

2

There are multiple ways to do so.

  1. Using vars():
>>> a = ['a', 'b', 'c']
>>> vars()[a[0]] = 5
>>> a
5
  1. Using exec():
>>> exec("b=5")
>>> b
5

Dynamically executing code in exec can be dangerous especially if you are using user input. So make sure you know what you are doing.

There are also other methods to achieve this which are described in this G4G article here.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.