list - create a python dictionary based on another dictionary -


i have the following dict contains following data:

response = {"status":"error","email":"email_invalid","name":"name_invalid"} 

i trying create new dict based on 'response' suposed following:

{'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'} 

so far have been able following:

ret = {} k in response:         if k != 'status':                 ret[k+"_label"] = convert(response[k])                 ret[k] = response[k]         else:             ret[k] = convert(response[k]) 

where 'convert' function translates each value of response. example name_invalid converted 'no special characters allowed.' , on. here output of above code doing:

{"status":"error","name_label":"no special characters allowed.", "email_label":"invalid email","name":"name_invalid","email":"email_invalid"} 

i getting problem creating rest of dictionary. 1 key 'api_error'. efficient way of doing that?

import pprint  response = {"status": "error", "email": "email_invalid", "name":             "name_invalid"}   def convert(label):     return {'name_invalid': 'no special characters allowed',             'email_invalid': 'invalid email',             'error': 'error'}[label]  ret = {} k in response:     if k != 'status':         ret[k + "_label"] = convert(response[k])         ret[k] = response[k]         info = {'converted_value': ret[k + "_label"],                 'field': k,                 'value': response[k]}         (ret.setdefault('api_error', {})             .setdefault('list', [])             .append(info))     else:         ret[k] = convert(response[k])         ret.setdefault('api_error', {})['status'] = ret[k] pprint.pprint(ret) 

yields

{'api_error': {'list': [{'converted_value': 'invalid email',                          'field': 'email',                          'value': 'email_invalid'},                         {'converted_value': 'no special characters allowed',                          'field': 'name',                          'value': 'name_invalid'}],                'status': 'error'},  'email': 'email_invalid',  'email_label': 'invalid email',  'name': 'name_invalid',  'name_label': 'no special characters allowed',  'status': 'error'} 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -