Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 924
summer Avatar asked Oct 25 '25 08:10

summer


1 Answers

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 sets and dicts.

like image 127
Ethan Furman Avatar answered Oct 26 '25 23:10

Ethan Furman