Convert String Name to a variable name

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Gunnar Hurtig
    New Member
    • Feb 2008
    • 4

    Convert String Name to a variable name

    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
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Following are a couple of ways:
    Code:
    >>> 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?

    Comment

    • Gunnar Hurtig
      New Member
      • Feb 2008
      • 4

      #3
      Thanks

      It was the %s=%s %(a,z) that I over looked
      Problem solved!

      Comment

      • Gunnar Hurtig
        New Member
        • Feb 2008
        • 4

        #4
        Not quite

        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??

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          Something like this:
          Code:
          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.

          Comment

          Working...