<p>可以使用递归:</p>
<pre><code>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])
</code></pre>
<p>输出:</p>
^{pr2}$
<p>这将产生对应于不等值的键。在</p>
<p>编辑:无列表理解:</p>
<pre><code>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)))
</code></pre>
<p>输出:</p>
<pre><code>['category2', 2, 3, 'section2']
</code></pre>
<p>这个解决方案利用了生成器(因此有<code>yield</code>语句),它动态地存储生成的值,只记住它停止的地方。这些值可以通过将返回的结果强制转换为一个列表来获得。<code>yield</code>使累积值差异更容易,并且不需要在函数或全局变量中保留额外的参数。在</p>