Python: the type of the key must be immutable in the dictionary, but why can I let an instance of the node class be the key?

Regardless of a dictionary in python or a hashmap in Java, the key can be an instance of the node class.

But when I read the python tutorial it says:

The keys are unique in the dictionary, and the values ​​may not be available. Dictionary values ​​can be of any type, but keys must be immutable data types such as strings, numbers, or tuples.

I feel embarrassed! # Sorry for my bad expression! :(

Sample code:

class RandomListNode:
    def __init__(self, x):
        self.label = x
        self.next = None
        self.random = None

dict = {}
node1 = RandomListNode(10)
node2 = RandomListNode(5)
dict[node1] = node2
print dict[node1].label #5

      

Summary: Hashable (hash value will not be changed), or immutable object can be a key value. Ref: https://docs.python.org/2/glossary.html#term-hashable

+3


source to share


1 answer


By default, instances of a class are unique and therefore can be used as keys.



The actual limitation is the presence of a method __hash__

in the class. If you add your own method __eq__

, you must also add your own method __hash__

, which is still considered "immutable", but make sure your hash value is not mutated or your entries will not be fetched from set

and dict

s.

+4


source







All Articles