In Python, the list type cannot be a dictionary key.
key = [1, 2, 3]
table = {key: 1} #error
The reason is that the list type can change its state. For example
key1 = [1]
key2 = [2]
table = {key1: 1, key2: 2}
key1[0] = 2
It would be a problem if you could do something like that. But I want to use the array as a key! In such a case, use tuple.
Libraries that handle their own arrays include numpy and sympy. What is the treatment in these? Whether or not an object can be used as a key depends on whether or not there is a `` `hash``` function, so let's take a look.
from sympy import Matrix, ImmutableMatrix
import numpy as np
# sympy
Matrix([1, 2]).__hash__ # None
ImmutableMatrix([1, 2]).__hash__ # not None
# numpy
a = np.array([1, 2])
a.__hash__ # None
a.flags.writeable = False
a.__hash__ # None
So, it was useless even if it was not writable with numpy. Well, it's natural because it can be returned. .. (By the way, it seems that you can copy with as_immutable of sympy etc. Even if you make changes to the original, the result will not change.)
Recommended Posts