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?
You can use difflib, but the use unittest method seems more appropriate to me. But if you wanted to use difflib. Let’s say say the following are the two dicts.
You may need to convert them to strings (or list of strings) and then go about using difflib as a normal business.
THe output would be: