如何比较嵌套dict

2024-03-29 11:50:03 发布

您现在位置:Python中文网/ 问答频道 /正文

a_standard = {
    'section1': {
        'category1': 1,
        'category2': 2
    },
    'section2': {
        'category1': 1,
        'category2': 2
    }

}

a_new = {
    'section1': {
        'category1': 1,
        'category2': 2
    },
    'section2': {
        'category1': 1,
        'category2': 3
    }

}

我想找出a_standarda_new之间的区别,即a_new[section2][category2]之间的差值是2和{}

我应该把每一个都转换成一个集合,然后做差分或循环并比较dict吗?在


Tags: new差分dictstandard区别section1section2category2
2条回答

如果密钥相同,则可以执行此操作:

def find_diff(dict1, dict2):
    differences = []
    for key in dict1.keys(): 
        if type(dict1[key]) is dict:
            return find_diff(dict1[key], dict2[key])
        else:
            if not dict1[key] == dict2[key]:
                differences.append((key, dict1[key], dict2[key]))
    return differences

我正在打电话,如果语法有点混乱,很抱歉。在

可以使用递归:

a_standard = {
'section1': {
    'category1': 1,
    'category2': 2
},
'section2': {
    'category1': 1,
    'category2': 2
 }

}

a_new = {
'section1': {
    'category1': 1,
    'category2': 2
},
'section2': {
    'category1': 1,
    'category2': 3
 }

}
def differences(a, b, section=None):
    return [(c, d, g, section) if all(not isinstance(i, dict) for i in [d, g]) and d != g else None if all(not isinstance(i, dict) for i in [d, g]) and d == g else differences(d, g, c) for [c, d], [h, g] in zip(a.items(), b.items())]

n = filter(None, [i for b in differences(a_standard, a_new) for i in b])

输出:

^{pr2}$

这将产生对应于不等值的键。在

编辑:无列表理解:

def differences(a, b, section = None):
  for [c, d], [h, g] in zip(a.items(), b.items()):
      if not isinstance(d, dict) and not isinstance(g, dict):
         if d != g:
            yield (c, d, g, section)
      else:
          for i in differences(d, g, c):
             for b in i:
               yield b
print(list(differences(a_standard, a_new)))

输出:

['category2', 2, 3, 'section2']

这个解决方案利用了生成器(因此有yield语句),它动态地存储生成的值,只记住它停止的地方。这些值可以通过将返回的结果强制转换为一个列表来获得。yield使累积值差异更容易,并且不需要在函数或全局变量中保留额外的参数。在

相关问题 更多 >