I want to take two dictionaries and print a diff of them. This diff should include the differences in keys AND values. I've created this little snippet to achieve the results using built-in code in the unittest
module. However, it's a nasty hack since I have to subclass unittest.TestCase
and provide a runtest()
method for it to work. In addition, this code will cause the application to error out since it will raise an AssertError
when there are differences. All I really want is to print the diff.
import unittest
class tmp(unittest.TestCase):
def __init__(self):
# Show full diff of objects (dicts could be HUGE and output truncated)
self.maxDiff = None
def runTest():
pass
_ = tmp()
_.assertDictEqual(d1, d2)
I was hoping to use the difflib
module, but it looks to only work for strings. Is there some way to work around this and still use difflib
?
The compare method cmp() is used in Python to compare values and keys of two dictionaries. If method returns 0 if both dictionaries are equal, 1 if dic1 > dict2 and -1 if dict1 < dict2.
According to the python doc, you can indeed use the == operator on dictionaries.
Adapted from the cpython source:
https://github.com/python/cpython/blob/01fd68752e2d2d0a5f90ae8944ca35df0a5ddeaa/Lib/unittest/case.py#L1091
import difflib
import pprint
def compare_dicts(d1, d2):
return ('\n' + '\n'.join(difflib.ndiff(
pprint.pformat(d1).splitlines(),
pprint.pformat(d2).splitlines())))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With