I'm pretty new to Python numpy. I was attempted to use numpy array as the key in dictionary in one of my functions and then been told by Python interpreter that numpy array is not hashable. I've just found out that one way to work this issue around is to use repr()
function to convert numpy array to a string but it seems very expensive. Is there any better way to achieve same effect?
Update: I could create a new class to contain the numpy array, which seems to be right way to achieve what I want. Just wondering if there is any better method?
update 2: Using a class to contain data in the array and then override __hash__
function is acceptable, however, I'd prefer the solution provided by @hpaulj. Convert the array/list
to a tuple
fits my need in a better way as it does not require an additional class.
You may use the data in numpy array to create a hash which could be used as a key for dictionary.
Also as expected, the Numpy array performed faster than the dictionary.
For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable. Values, on the other hand, can be any type and can be used more than once.
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.
array
and then override __hash__
function to amend the way how it is hashed as mentioned by ZdaR
array
to a tuple
, 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.
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