Reputation: 321
I'm writing tests using pytest
. I have two dictionaries with numpy
arrays that looks something like:
dict_1 = {
'test_1': np.array([-0.1, -0.2, -0.3]),
'test_2': np.array([-0.4, -0.5, -0.6]),
'test_3': np.array([-0.7, -0.8, -0.9]),
}
When I try to compare two of these using assert dict_1 == dict_2
, I get an error saying
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
And it seems like any()
and all()
only work on lists. Would I have to run a loop in those two dicts and compare each values using all()
or any()
?
Upvotes: 1
Views: 899
Reputation: 157
You can use numpy.testing.assert_equal
:
np.testing.assert_equal(dict_1,dict_2)
For more information, here is a link to the numpy
documentation for np.testing.assert_equal
.
Upvotes: 4
Reputation: 19251
You can check to make sure that the key sets are equal, and then make sure that, for each key, the elements in the corresponding arrays are the same using a generator comprehension and .all()
:
assert dict_1.keys() == dict_2.keys() and \
all((dict_1[key] == dict_2[key]).all() for key in dict_1.keys())
Upvotes: 2