Compare dictionaries for close matching

I am looking for a good way to compare two dictionaries that contain matrix information. So, the structure of my dictionaries is as follows: both dictionaries have the same keys:

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, ...

If I have matrices, i.e. list listings i can use numpy.allclose. Is there something similar for dictionaries or is there a good way to turn my dictionaries into such matrices?

Thank you for your help.

+4
source share
3 answers

The 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')
+5
source

numpy, . significant.

import numpy as np

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}

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 True

compare_dicts(dict_1, dict_2)

dict dicts.

. numpy .

+2

You can use OrderedDictto get the default values ​​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
0
source

All Articles