字典方法而不是 exec 方法



我有以下变量:

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}]

这几乎是我定义的函数的输出。

毫无疑问,我知道我的函数的输出将永远是JointFlag和Strategy。至于 Output 中的其他变量,它们可能存在也可能不存在(甚至可能有更新的变量或顺序不同!

我听说字典是比exec更好的方法,我只是想知道如何处理这个问题。

在我定义的函数结束时,它将具有以下字符串:

return JointFlag, Strategy

这是我当前正在使用的exec命令。

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

您可以将Output转换为字典

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

甚至

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

,然后使用

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()
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']

最新更新