Python - Alternative for using numpy array as key in dictionary
If you want to quickly store a numpy.ndarray
as a key in a dictionary, a fast option is to use ndarray.tobytes() which will return a raw python bytes
string which is immutable
my_array = numpy.arange(4).reshape((2,2))
my_dict = {}
my_dict[my_array.tobytes()] = None
After done some researches and reading through all comments. I think I've known the answer to my own question so I'd just write them down.
- Write a class to contain the data in the
array
and then override__hash__
function to amend the way how it is hashed as mentioned by ZdaR - Convert this
array
to atuple
, which makes the list hashable instantaneously.Thanks to hpaulj
I'd prefer method No.2 because it fits my need better, as well as simpler. However, using a class might bring some additional benefits so it could also be useful.