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 sets and dicts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With