Search code examples
pythonpython-3.xdictionarypython-exec

A dictionary method instead of exec method


I have the following variable:

Output=[{'name': 'AnnualIncome', 'value': 5.0},
 {'name': 'DebtToIncome', 'value': 5.0},
 {'name': 'Grade', 'value': 'A'},
 {'name': 'Home_Ownership', 'value': 'Rent'},
 {'name': 'ID', 'value': 'ID'},
 {'name': 'InitialListing_Status', 'value': 'f'},
 {'name': 'JointFlag', 'value': 0.0},
 {'name': 'LateFeeReceived_Total', 'value': 5.0},
 {'name': 'LoanAmount', 'value': 5.0},
 {'name': 'OpenCreditLines', 'value': 5.0},
 {'name': 'Strategy', 'value': 'Reject'},
 {'name': 'Term', 'value': '60 months'},
 {'name': 'TotalCreditLines', 'value': 5000.0}]

which is almost the output of my defined function.

Without doubt, I know that the output of my function will always be JointFlag and Strategy. As for the other variables in Output, they may or may not exist (there may even be newer ones or in a different order!)

I heard that dictionary is a much better method than exec and I'm just curious to know how to approach this.

At the end of my defined function it will have the following string:

return JointFlag, Strategy

Here is an exec command that I am currently using.

def execute():
    #Some random codes which leads to Output variable

    for Variable in range(len(Outputs)):
        exec(f"{list(Outputs[Variable].values())[0]} = r'{list(Outputs[Variable].values())[1]}'")
    return JointFlag, Strategy

Solution

  • You can convert Output to dictionary

    variables = dict()
    
    for item in Output:
        variables[item["name"]] = item["value"]
    

    or even

    variables = dict( (item["name"],item["value"]) for item in Output )
    

    and then use

    return variables["JointFlag"], variables["Strategy"]
    

    def execute():
        Output = [
         {'name': 'AnnualIncome', 'value': 5.0},
         {'name': 'DebtToIncome', 'value': 5.0},
         {'name': 'Grade', 'value': 'A'},
         {'name': 'Home_Ownership', 'value': 'Rent'},
         {'name': 'ID', 'value': 'ID'},
         {'name': 'InitialListing_Status', 'value': 'f'},
         {'name': 'JointFlag', 'value': 0.0},
         {'name': 'LateFeeReceived_Total', 'value': 5.0},
         {'name': 'LoanAmount', 'value': 5.0},
         {'name': 'OpenCreditLines', 'value': 5.0},
         {'name': 'Strategy', 'value': 'Reject'},
         {'name': 'Term', 'value': '60 months'},
         {'name': 'TotalCreditLines', 'value': 5000.0}
        ]
    
        variables = dict()
    
        for item in Output:
            variables[item["name"]] = item["value"]
    
        #variables = dict((item["name"],item["value"]) for item in Output)
        print(variables)
    
        return variables["JointFlag"], variables["Strategy"]
    
    execute()