'How to introduce relative/absolute tolerance in assertDictEqual?
Is there a built-in method or, alternatively, a quick and efficient way for assertDictEqual()
to have the same functionality as that of rtol
and/or atol
for asset_frame_equal()
in pandas.testing
?
I want to be able to compare two dictionaries for equality of values corresponding to the same key, where they pass as equal when the values are close to each other within a given tolerance limit. Similar to what atol/rtol does for frame_equal.
MRE:
import numpy as np
def assert_dicts_almost_equal(d1, d2, rtol=0.01, atol=0.1):
assert len(d1) == len(d2), 'Unequal number of elements.'
for key in d1:
try:
np.testing.assert_allclose(d1[key], d2[key], rtol=rtol, atol=atol)
except AssertionError as msg:
print('Assertion Error for {key}'.format(key=key))
print(msg)
Data:
d = {'A': 0.49, 'B': 0.51}
d0 = {'A': 0.4999999999999991, 'B': 0.5000000000000007, 'C': np.nan}
d1 = {'A': 0.3105572709904508, 'B': 0.5030302993151613, 'C': np.nan}
d2 = {'A': 0.4813463081397519, 'B': 0.5104397084554964, 'C': np.nan}
d3 = {'A': 0.4740668937066489, 'B': 0.5144020381674881, 'C': np.nan}
Tests:
assert_dicts_almost_equal(d0, d)
assert_dicts_almost_equal(d0, d1)
assert_dicts_almost_equal(d0, d2)
assert_dicts_almost_equal(d0, d3)
Only the first two will raise Assertion Error, the rest will pass.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|