Implementation example of python nested dictionary comparison value and value

Implementation example of python nested dictionary comparison value and value

This article introduces python nested dictionary comparison values, values, and sharing them for your reference and learning through examples. Let's take a look at the detailed introduction together.
Example code    
#value import types
allGuests = {'Alice': {'apples': 5, 'pretzels': {'12':{'beijing':456}}},
  'Bob': {'ham sandwiches': 3, 'apple': 2},
  'Carol': {'cups': 3, 'apple pies': 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:

Comparison of size

defbijiaodict(dict1,dict2):
 fork,vindict1.items():
 fork2,v2indict2.items():
  ifk == k2andv == v2:
  print('dict1=dict2')
  else:
  print('dict1!=dict2')
dict1={'2':'6'}
dict2={2:{1:{1:8}}}
bijiaodict(dict1,dict2)

result:

Get the value of a key in the case of a python dictionary nested dictionary

Just recently, I was writing a test program for an interface in python, during which I used to parse a dictionary to get the value of a certain key, because the format of the dictionary returned by multiple interfaces is not fixed and there are multiple levels of nesting. In the dictionary method, I didn't find a method that can directly achieve the purpose, so I wrote a program myself. Share with everyone:

#coding: utf-8
import types
 
#Get the value corresponding to 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 #such
 
as
dicttest={"result":{"code":"110002","msg":"device serial number or verification code error"}}
ret=dict_get(dicttest, 'msg' , None)
print(ret)
Summary
The above is the whole content of this article. I hope the content of this article has certain reference and learning value for everyone's study or work.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324824426&siteId=291194637