Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 314
swot Avatar asked Oct 27 '14 14:10

swot


People also ask

Can two dictionaries be compared?

Using Loop to Compare Two Dictionaries Here we are checking the equality of two dictionaries by iterating through one of the dictionaries keys using for loop and checking for the same keys in the other dictionaries.

Can we compare 2 dictionaries in Python?

The compare method cmp() is used in Python to compare values and keys of two dictionaries. If method returns 0 if both dictionaries are equal, 1 if dic1 > dict2 and -1 if dict1 < dict2.

How do you compare Dicts?

For simple dictionaries, comparing them is usually straightforward. You can use the == operator, and it will work.


1 Answers

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')
like image 106
Hannes Ovrén Avatar answered Nov 15 '22 07:11

Hannes Ovrén