我有以下包含以下数据的字典:
response = {"status":"ERROR","email":"EMAIL_INVALID","name":"NAME_INVALID"}
我正在尝试基于“响应”创建一个新的字典,该字典应该如下所示:
{'api_error': {'list': [{'converted_value': 'No special characters allowed.',
'field': 'name',
'value': 'NAME_INVALID'},
{'converted_value': 'invalid email',
'field': 'email',
'value': 'EMAIL_INVALID'}],
'status': 'ERROR'},
'email': 'EMAIL_INVALID',
'email_label': 'invalid email',
'name': 'NAME_INVALID',
'name_label': 'No special characters allowed.',
'status': 'ERROR'}
到目前为止,我已经能够做到以下几点:
ret = {}
for k in response:
if k != 'status':
ret[k+"_label"] = convert(response[k])
ret[k] = response[k]
else:
ret[k] = convert(response[k])
其中 'convert' 函数转换响应的每个值。例如 NAME_INVALID 被转换为“不允许特殊字符”。等等。以下是上述代码正在执行的操作的输出:
{"status":"ERROR","name_label":"No special characters allowed.",
"email_label":"invalid email","name":"NAME_INVALID","email":"EMAIL_INVALID"}
我在创建字典的其余部分时遇到问题。键是“api_error”的那个。这样做最有效的方法是什么?