440,675 Members | 2,270 Online
Need help? Post your question and get tips & solutions from a community of 440,675 IT Pros & Developers. It's quick & easy.

# Convert String Name to a variable name

 P: 4 How do I convert a string name into a variable name? example L=['a','b'] I want to create two variables from L so that I can assign values to them. say a=4 b=5 Dec 17 '08 #1
4 Replies

 Expert Mod 2.5K+ P: 2,851 Following are a couple of ways: Expand|Select|Wrap|Line Numbers >>> L=['a','b'] >>> V=[4,5] >>> for var in zip(L,V): ...     exec "%s=%s" % (var[0], var[1]) ...      >>> a 4 >>> b 5 >>> V=[6,7] >>> dd = dict(zip(L,V)) >>> dd {'a': 6, 'b': 7} >>> globals().update(dd) >>> a 6 >>> b 7 >>>  Why would you want to do this? Dec 17 '08 #2

 P: 4 It was the %s=%s %(a,z) that I over looked Problem solved! Dec 18 '08 #3

 P: 4 Actually I need something like this: L=['G123','G452', 'Had3'......] #Not sure whats going to be in L until run into G123= [112,234,113,..] #Values in list determined during run. G452=[456, 789,0,0...] and then: L2=[G123,G452,Had3...] then send L2 off to another def with the named variables G123 .... Is this a little clearer?? Dec 18 '08 #4

 Expert Mod 2.5K+ P: 2,851 Something like this: Expand|Select|Wrap|Line Numbers L=['G123','G452', 'Had3'] for item in L:     globals().update({item: return_a_list()})   for item in L:     print eval(item) I do not understand what you are doing, but I think you should consider organizing and passing data with dictionaries. Dec 18 '08 #5