Created
April 23, 2014 16:10
-
-
Save openinx/11221677 to your computer and use it in GitHub Desktop.
How to compare two dict.
This file contains hidden or 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 assertDictMatch(self, d1, d2, approx_equal=False, tolerance=0.001): | |
"""Assert two dicts are equivalent. | |
This is a 'deep' match in the sense that it handles nested | |
dictionaries appropriately. | |
NOTE: | |
If you don't care (or don't know) a given value, you can specify | |
the string DONTCARE as the value. This will cause that dict-item | |
to be skipped. | |
""" | |
def raise_assertion(msg): | |
d1str = d1 | |
d2str = d2 | |
base_msg = ('Dictionaries do not match. %(msg)s d1: %(d1str)s ' | |
'd2: %(d2str)s' % | |
{'msg': msg, 'd1str': d1str, 'd2str': d2str}) | |
raise AssertionError(base_msg) | |
d1keys = set(d1.keys()) | |
d2keys = set(d2.keys()) | |
if d1keys != d2keys: | |
d1only = d1keys - d2keys | |
d2only = d2keys - d1keys | |
raise_assertion('Keys in d1 and not d2: %(d1only)s. ' | |
'Keys in d2 and not d1: %(d2only)s' % | |
{'d1only': d1only, 'd2only': d2only}) | |
for key in d1keys: | |
d1value = d1[key] | |
d2value = d2[key] | |
try: | |
error = abs(float(d1value) - float(d2value)) | |
within_tolerance = error <= tolerance | |
except (ValueError, TypeError): | |
# If both values aren't convertable to float, just ignore | |
# ValueError if arg is a str, TypeError if it's something else | |
# (like None) | |
within_tolerance = False | |
if hasattr(d1value, 'keys') and hasattr(d2value, 'keys'): | |
self.assertDictMatch(d1value, d2value) | |
elif 'DONTCARE' in (d1value, d2value): | |
continue | |
elif approx_equal and within_tolerance: | |
continue | |
elif d1value != d2value: | |
raise_assertion("d1['%(key)s']=%(d1value)s != " | |
"d2['%(key)s']=%(d2value)s" % | |
{ | |
'key': key, | |
'd1value': d1value, | |
'd2value': d2value, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment