Python nested dictionary comparison value and value implementation example, python nested dictionary example
Preface
This article provides examples to show you how to compare the values and values of the python nested dictionary and share the values for your reference and learning. I will not talk about them much here. Let's take a look at the detailed introduction.
Sample Code
# Value import typesallGuests = {'Alice ': {'apples': 5, 'pretzels ': {'12': {'beijing': 456 }}, 'bob ': {'ham sandwiches ': 3, 'apple': 2}, 'carol': {'cups ': 3, 'applies': 1} def dictget (dict1, obj, default = None): for k, v in dict1.items (): if k = obj: print (v) else: if type (v) is dict: re = dictget (v, obj) if re is not default: print (re) dictget (allGuests, 'beijing ')
Result:
Compare size
def bijiaodict(dict1,dict2): for k,v in dict1.items(): for k2,v2 in dict2.items(): if k==k2 and v==v2: print('dict1=dict2') else: print('dict1!=dict2')dict1={'2':'6'}dict2={2:{1:{1:8}}}bijiaodict(dict1,dict2)
Result:
Obtain the value of a key when the python dictionary is nested.
In the test program that recently writes an interface using python, the dictionary is used to obtain the value of a key. The dictionary format returned by multiple interfaces is not fixed and multiple layers of nesting exist. In the dictionary method, no method can be directly achieved, so I wrote a program. Share with you:
# Coding: utf-8import types # Get the value of the objkey in the dictionary, suitable for dictionary nesting # dict: dictionary # objkey: target key # default: default value returned when not found def dict_get (dict, objkey, default): tmp = dict for k, v in tmp. items (): if k = objkey: return v else: if type (v) is types. dictType: ret = dict_get (v, objkey, default) if ret is not default: return ret return default # For example, dicttest = {"result": {"code": "110002 ", "msg": "Incorrect device serial number or verification code"} ret = dict_get (dicttest, 'msg ', None) print (ret)
Summary
The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.