Home > Net >  How to make values in a list become variables and set values to them? - python
How to make values in a list become variables and set values to them? - python

Time:09-21

I have two lists, one a list with a set of strings, and another list with a set of various values of strings or numbers.

I want to make each value from the first list to be a new variable with the same name and set its value to a value from the second list with the same position in the list.

So for example,

list_1 = ['Part_Number', 'Qty']
list_2 = ['RE12345', 5]

# into something like this 

Part_Number = 'RE12345'
Qty = 5

CodePudding user response:

I guess you are looking something in the effect of

for var,val in zip(list_1, list_2):
    locals()[var]=val

Not sure it is the best way, but it does what you want, if I understand your question correctly.

CodePudding user response:

You can do something like this:

for i in range(len(list_1)):          
    globals()[list_1[i]] = list_2[i]
    print(eval(list_1[i])) 

print statement shows the values of each variable

  • Related