Obtain the value and pythonvalue of a key when the python dictionary is nested.

Source: Internet
Author: User

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)

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.