python 比较两个字典的结构差异

  • Post author:
  • Post category:python


# 值相等

EQUAL = ‘=’

# 值不等

DIFF = ‘!’

# 独有key

MORE = ‘+’

# 缺失key

LACK = ‘-‘


class CompareTwoDict(object):

“””比较两个字典差异”””

def __init__(self, dict1, dict2):

self.dict1 = dict1

self.dict2 = dict2

self.key_list = self.keys(dict1, dict2)

self.result = {}

def compare(self, key):

“””比较一个key”””

# 这里默认value不是None

v1 = self.dict1.get(key)

v2 = self.dict2.get(key)

# 如果都是字典继续深入比较

if (type(v1) == dict) and (type(v2) == dict):

self.result[key] = CompareTwoDict(v1, v2).main()

else:

self.result[key] = self.diff(v1, v2)

@staticmethod

def diff(v1, v2):

“””比较value差异”””

if (v1 is not None) and (v2 is not None):

if v1 == v2:

return EQUAL

else:

return DIFF

elif v1 is not None:

return MORE

else:

return LACK

@staticmethod

def keys(dict1, dict2):

“””获取所有key”””

return list(set(dict1.keys() + dict2.keys()))

def main(self):

for k in self.key_list:

self.compare(k)

return self.result


d1 = {“class”: {“l1”: {“name”: “jack”, ‘age’: {“j”: 1}}}, ‘l2’: {“name”: ‘laowang’, “age”: 13}}

d2 = {“class”: {“l1”: {“name”: “jacks”, ‘age’: {‘k’: 3}}}, ‘l2’: {“name”: ‘laowang’, “age”: 1, ‘gender’: ‘male’}}

if __name__ == ‘__main__’:

cmp = CompareTwoDict(d1, d2)

print(cmp.main())



版权声明:本文为weixin_41085315原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。