swot
swot

Reputation: 278

Compare Dictionaries for close enough match

I am looking for a good way to compare two dictionaries which contain the information of a matrix. So the structure of my dictionaries are the following, both dictionaries have identical 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 to matrices, i.e. lists of list, I can use numpy.allclose. Is there something similar for dictionaries or is there a nice way to transform my dictionaries into such matrices?

Thanks for your help.

Upvotes: 6

Views: 1427

Answers (3)

Kasravnd
Kasravnd

Reputation: 107347

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

Upvotes: 0

Manu
Manu

Reputation: 3452

There is a numpy-function, used in unit testing to compare 2 numbers. You can set the desired precision via 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)

This will take the keys from one dict and compare each item in both dicts.

See the details for the numpy-function used here.

Upvotes: 2

Hannes Ovrén
Hannes Ovrén

Reputation: 21841

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')

Upvotes: 6

Related Questions