Skip to content

Instantly share code, notes, and snippets.

@nzjrs nzjrs/
Created Jan 26, 2017

What would you like to do?
def dict_diff1(first, second, NO_KEY='<KEYNOTFOUND>'):
""" 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 NO_KEY.
@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], NO_KEY)
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] = (NO_KEY, second[key])
return diff
def dict_diff2(dict_a, dict_b):
return dict([
(key, dict_b.get(key, dict_a.get(key)))
for key in set(dict_a.keys()+dict_b.keys())
if (
(key in dict_a and (not key in dict_b or dict_a[key] != dict_b[key])) or
(key in dict_b and (not key in dict_a or dict_a[key] != dict_b[key]))
def dict_diff3(d1, d2, NO_KEY='<KEYNOTFOUND>'):
d1k = set(d1)
d2k = set(d2)
both = d1k & d2k
diff = {k:(d1[k], d2[k]) for k in both if d1[k] != d2[k]}
diff.update({k:(d1[k], NO_KEY) for k in d1k - both})
diff.update({k:(NO_KEY, d2[k]) for k in d2k - both})
return diff
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.