Search code examples
pythonvariableswxpythonplaceholder

working with placeholder in variable names in Python, wx.python


I am working with wxpython and want to shorten my qode by working with loops. The following example is not working and I am wondering how to get it work.

Keys = ['Q_geo_ges_h','Q_geo_ges_k']
Values = [12.6,1.943]
for key,value in Keys,Values:
    'self.%s'%key = wx.TextCtrl(self,-1,value=str(value))

Is there any way to assign a variable from a list of strings?


Solution

  • Using zip to make a sequence of key, value pairs.

    >>> keys = ['Q_geo_ges_h', 'Q_geo_ges_k']
    >>> values = [12.6, 1.943]
    >>> zip(keys, values)
    [('Q_geo_ges_h', 12.6), ('Q_geo_ges_k', 1.943)]
    

    And use setattr to set attribute:

    keys = ['Q_geo_ges_h', 'Q_geo_ges_k']
    values = [12.6, 1.943]
    for key, value in zip(keys, values):
        setattr(self, key, wx.TextCtrl(self, -1, value=str(value))