By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,675 Members | 2,270 Online
Bytes IT Community
+ Ask a Question
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
Share this Question
Share on Google+
4 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Following are a couple of ways:
Expand|Select|Wrap|Line Numbers
  1. >>> L=['a','b']
  2. >>> V=[4,5]
  3. >>> for var in zip(L,V):
  4. ...     exec "%s=%s" % (var[0], var[1])
  5. ...     
  6. >>> a
  7. 4
  8. >>> b
  9. 5
  10. >>> V=[6,7]
  11. >>> dd = dict(zip(L,V))
  12. >>> dd
  13. {'a': 6, 'b': 7}
  14. >>> globals().update(dd)
  15. >>> a
  16. 6
  17. >>> b
  18. 7
  19. >>> 
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

bvdet
Expert Mod 2.5K+
P: 2,851
Something like this:
Expand|Select|Wrap|Line Numbers
  1. L=['G123','G452', 'Had3']
  2. for item in L:
  3.     globals().update({item: return_a_list()})
  4.  
  5. for item in L:
  6.     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

Post your reply

Sign in to post your reply or Sign up for a free account.