Last active
September 30, 2016 06:33
-
-
Save ewenchou/924336038ad5f444f51b00d794ceea05 to your computer and use it in GitHub Desktop.
Check for difference in key/value of one dictionary compared to another
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def dict_diff(d1, d2): | |
"""Checks if all the key/values in d1 are in d2. | |
Returns True if there is a difference, i.e. | |
* There is a key in d1 that is not in d2 | |
* There is a key/value in d1 that is different in d2 | |
Otherwise, returns False. | |
""" | |
for k, v in d1.iteritems(): | |
if k not in d2: | |
return True | |
if isinstance(v, dict): | |
if dict_diff(v, d2[k]): | |
return True | |
else: | |
if v != d2[k]: | |
return True | |
return False | |
def main(): | |
d1 = {'a': 1, 'b': 2, 'nested': {'a': 1, 'b': 2}} | |
d2 = {'a': 1, 'b': 2, 'c': 3, 'nested': {'a': 1, 'b': 2, 'c': 3}} | |
print "d1 diff d2: {} (should be False)".format(dict_diff(d1, d2)) | |
d3 = {'a': 1, 'b': 5, 'c': 3, 'nested': {'a': 1, 'b': 2, 'c': 3}} | |
print "d1 diff d3: {} (should be True)".format(dict_diff(d1, d3)) | |
d4 = {'a': 1, 'c': 3} | |
print "d1 diff d4: {} (should be True)".format(dict_diff(d1, d4)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment