Skip to content
Advertisement

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()?

Advertisement

Answer

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.

Advertisement