0

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
Jin Khor
  • 21
  • 3

2 Answers2

0

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()
furas
  • 134,197
  • 12
  • 106
  • 148
  • 1
    ```variables = dict( (item["name"],item["value"]) for item in Output )``` This is a winner for me. Thanks! – Jin Khor Aug 19 '19 at 02:37
0
def execute():
    my_dict={}
    for Variable in range(len(Output)):
        my_dict[list(Output[Variable].values())[0]] = list(Output[Variable].values())[1]
    return my_dict['JointFlag'],my_dict['Strategy']
sarath sg
  • 1
  • 2