Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Alternative for using numpy array as key in dictionary

Tags:

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.

like image 530
JZ_42 Avatar asked Sep 24 '16 09:09

JZ_42


People also ask

Can a NumPy array be a key in a dictionary?

You may use the data in numpy array to create a hash which could be used as a key for dictionary.

Are NumPy arrays faster than dictionary?

Also as expected, the Numpy array performed faster than the dictionary.

What can be used as keys in Python dictionaries?

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.


2 Answers

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
like image 138
Peter Olson Avatar answered Oct 13 '22 14:10

Peter Olson


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.

  1. 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
  2. Convert this 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.

like image 27
JZ_42 Avatar answered Oct 13 '22 14:10

JZ_42