python

extract variables from list and run a loop


I have a scenario like below in Python.

contents of run_main.py are below

system_code = 'Ind'

if system_code == 'Ind':
    ft_tb = ['B_FT', 'S_FT', 'D_FT']
    bt_tb = ['B_BT', 'S_BT', 'D_BT']
else:
    ft_tb = ['T_FT', 'T_FT', 'T_FT']
    bt_tb = ['T_BT', 'T_BT', 'T_BT']

Now I want to run below code in loop for each list based on system_code

for example:

if system_code == Ind
    
    # ft_tb list
    element_1, element_2, element_3 = ft_tb[:3]
    
    print("SELECT * FROM {} WHERE application = {}".format(element_1, element_3))
    print("DELETE FROM {} WHERE application = {}".format(element_2, element_3))
            
    # bt_tb list
    element_1, element_2, element_3 = bt_tb[:3]

    print("SELECT * FROM {} WHERE application = {}".format(element_1, element_3))
    print("DELETE FROM {} WHERE application = {}".format(element_2, element_3))
    

        

Solution

  • Use a list instead of multiple variables, then you can iterate over it.

    if system_code == 'Ind':
        sql_params = [
            {'select_tbl': 'B_FT', 'delete_tbl': 'S_FT', 'app': 'D_FT'},
            {'select_tbl': 'B_BT', 'delete_tbl': 'S_BT', 'app': 'D_BT'}
        ]
    else:
        sql_params = [
            {'select_tbl': 'T_FT', 'delete_tbl': 'T_FT', 'app': 'T_FT'},
            {'select_tbl': 'T_BT', 'delete_tbl': 'T_BT', 'app': 'T_BT'}
        ]
    
    if system_code == Ind:
        for p in sql_params:
            print(f"SELECT * FROM {p['select_tbl']} WHERE application = '{p['app']}'")
            print(f"DELETE * FROM {p['delete_tbl']} WHERE application = '{p['app']}'")