Compare Dictionaries for close enough match
Easiest way I could think of:
keylist = dict_1.keys()array_1 = numpy.array([dict_1[key] for key in keylist])array_2 = numpy.array([dict_2[key] for key in keylist])if numpy.allclose(array_1, array_2): print('Equal')else: print('Not equal')
There is a numpy-function, used in unit testing to compare 2 numbers. You can set the desired precision via significant
.
import numpy as npdict_1 = {("a","a"):0.01, ("a","b"): 0.02, ("a","c"): 0.00015}dict_2 = {("a","a"):0.01, ("a","b"): 0.018, ("a","c"): 0.00014}def compare_dicts(dict_1, dict_2, significant=2): for k in dict_1: try: np.testing.assert_approx_equal(dict_1[k], dict_2[k], significant=significant) except AssertionError: return False return Truecompare_dicts(dict_1, dict_2)
This will take the keys from one dict and compare each item in both dicts.
See the details for the numpy-function used here.
You can use OrderedDict
to get the values in default order and numpy.allclose
:
>>> import numpy>>> from collections import OrderedDict>>> dict_1 = {("a","a"):0.01, ("a","b"): 0.02, ("a","c"): 0.00015}>>> dict_2 = {("a","a"):0.01, ("a","b"): 0.018, ("a","c"): 0.00014}>>> d2=OrderedDict(sorted(dict_2.items(), key=lambda t: t)) #d2.values() -> [0.01, 0.018, 0.00014]>>> d1=OrderedDict(sorted(dict_1.items(), key=lambda t: t))>>> atol=0.0001 # as example>>> numpy.allclose(d1.values(),d2.values())False