Obtain the value and pythonvalue of a key when the python dictionary is nested.
Recently, a test program that writes an interface using python used a parsing dictionary to obtain the value of a key. Because the dictionary format returned by multiple interfaces is not fixed, multiple layers of nesting exist. In the dictionary method, I did not find a method that can directly achieve the goal (or because I did not know much about the dictionary method), so I wrote a program myself.
1 # coding: UTF-8 2 import types 3 4 # obtain the value of the objkey in the dictionary. It is applicable to dictionary nesting 5 # dict: dictionary 6 # objkey: target key 7 # default: the default value 8 def dict_get (dict, objkey, default) returned when no result is found: 9 tmp = dict10 for k, v in tmp. items (): 11 if k = objkey: 12 return v13 else: 14 if type (v) is types. dictType: 15 ret = dict_get (v, objkey, default) 16 if ret is not default: 17 return ret18 return default19 20 #21 dicttest = {"result ": {"code": "110002", "msg": "Incorrect device serial number or verification code"} 22 ret = dict_get (dicttest, 'msg ', None) 23 print (ret)