Matrix As Dictionary Key
I've just started using numpy and its matrix module (very very useful!), and I wanted to use a matrix object as the key of a dictionary, so I checked if matrix had the __hash__ met
Solution 1:
It would be wrong to use a mutable object as a key of a dictionary because its hash should change as soon as you change the data, but the value used on insertion will be kept.
On my tests, numpy at Python 3.2.2 raise a TypeError:
TypeError: unhashable type: 'matrix'
But on Python 2.7 it still allows hashing but the hash value never changes when you change data, so it is pretty useless as dictionary key because many matrix
objects being added to the dictionary having the same hash will degrade the hash table so insertion will be O(n^2)
instead of O(1)
.
Maybe they didn't remove the hash value to avoid breaking some API on Python 2.x, but do not rely on it!
Post a Comment for "Matrix As Dictionary Key"