Calculate difference in keys contained in two Python dictionaries

后端 未结 21 1436
眼角桃花
眼角桃花 2020-11-27 09:33

Suppose I have two Python dictionaries - dictA and dictB. I need to find out if there are any keys which are present in dictB but not

21条回答
  •  日久生厌
    2020-11-27 09:51

    Here is a solution for deep comparing 2 dictionaries keys:

    def compareDictKeys(dict1, dict2):
      if type(dict1) != dict or type(dict2) != dict:
          return False
    
      keys1, keys2 = dict1.keys(), dict2.keys()
      diff = set(keys1) - set(keys2) or set(keys2) - set(keys1)
    
      if not diff:
          for key in keys1:
              if (type(dict1[key]) == dict or type(dict2[key]) == dict) and not compareDictKeys(dict1[key], dict2[key]):
                  diff = True
                  break
    
      return not diff
    

提交回复
热议问题