<p>下面是指向一个函数的链接,该函数可以生成两个字典的“diff”,然后是其他注释/代码示例:</p>
<p><a href="http://code.activestate.com/recipes/576644-diff-two-dictionaries/" rel="nofollow noreferrer">http://code.activestate.com/recipes/576644-diff-two-dictionaries/</a></p>
<p>包括以下代码:</p>
<pre><code>KEYNOTFOUND = '<KEYNOTFOUND>' # KeyNotFound for dictDiff
def dict_diff(first, second):
""" Return a dict of keys that differ with another config object. If a value is
not found in one fo the configs, it will be represented by KEYNOTFOUND.
@param first: Fist dictionary to diff.
@param second: Second dicationary to diff.
@return diff: Dict of Key => (first.val, second.val)
"""
diff = {}
# Check all keys in first dict
for key in first.keys():
if (not second.has_key(key)):
diff[key] = (first[key], KEYNOTFOUND)
elif (first[key] != second[key]):
diff[key] = (first[key], second[key])
# Check all keys in second dict to find missing
for key in second.keys():
if (not first.has_key(key)):
diff[key] = (KEYNOTFOUND, second[key])
return diff
</code></pre>