Is There A Way To Instantiate Variables From Iterated Output In Python?
Say I have a list my_list = ['a','b','c'] and I have a set of values my_values = [1,2,3] Is there a way to iterate through my list and set the values of my_list equal to my
Solution 1:
This is probably hackery that you shouldn't do, but since the globals() dict has all the global variables in it, you can add them to the global dict for the module:
>>>my_list = ['a','b','c']>>>my_values = [1,2,3]>>>for k, v inzip(my_list, my_values):...globals()[k] = v...>>>a
1
>>>b
2
>>>c
3
But caveat emptor, best not to mix your namespace with your variable values. I don't see anything good coming of it.
I recommend using a normal dict instead to store your values instead of loading them into the global or local namespace.
Post a Comment for "Is There A Way To Instantiate Variables From Iterated Output In Python?"