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.
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.
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.
For simple dictionaries, comparing them is usually straightforward. You can use the == operator, and it will work.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With