gsamaras gsamaras - 2 years ago 63
Python Question

Alter the hash function of a dictionary

Following this question, we know that two different dictionaries,

for example, use the exact same hash function.

Is there any way to alter the hash function used by the dictionary?Negative answers also accepted!

Answer Source

You can't change the hash-function - the dict will call hash on the keys it's supposed to insert, and that's that.

However, you can wrap the keys to provide different __hash__ and __eq__-Methods.

class MyHash(object):
     def __init__(self, v):
         self._v = v

     def __hash__(self):
         return hash(self._v) * -1

     def __eq__(self, other):
         return self._v == other._v

If this actually helps anything with your original problem/question I doubt though, it seems rather a custom array/list-based data-structure might be the answer. Or not.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download