'Comparing two dictionaries with numpy arrays as values
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()
?
Solution 1:[1]
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
.
Solution 2:[2]
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())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | BrokenBenchmark |
Solution 2 | BrokenBenchmark |