简体   繁体   中英

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

No matter the dictionary in python or hash map in Java, the key can be an instance of node class.

But when I am reading the python tutorial, it says:

Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Feel confused! # Sorry for my poor expression!:(

Sample code is:

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 key value. Ref: https://docs.python.org/2/glossary.html#term-hashable

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

The actual constraint is the presence of a __hash__ method in the class. If you add a custom __eq__ method you must also add your own __hash__ method to still be considered "immutable" -- but make sure your hash value does not change with mutation, or your entries will not be retrievable from set s and dict s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM