Is it possible to use an object (class instance) as a dictionary key in Python?

I want to use an instance of a class as a dictionary key, for example:

classinstance = class() dictionary[classinstance] = 'hello world' 

Python doesn't seem to be able to handle classes as a dictionary key, or am I mistaken? Also, I could use a Tuple list, for example [(classinstance, helloworld), ...] instead of a dictionary, but it looks very unprofessional. Do you have any hint to fix this problem?

+7
source share
4 answers

Your instances must be hashed. The python glossary tells us:

A hashable object if it has a hash value that never changes during its life cycle (it needs the __hash__() method) and can be compared with other objects (it needs the __eq__() or __cmp__() method). Hashable objects that are compared equal must have the same hash value.

Hashability allows you to use an object as a dictionary key and a member of a set, as these data structures use an internal hash value.

All unused Pythons built-in objects are hashed, while there are no mutable containers (such as lists or dictionaries). Objects that are instances of custom classes are hashed by default; they are all compared unevenly, and their hash value is their id ().

+7
source

Try applying hash and eq methods in your class.

For example, here is a simple hashed dictionary class that I made:

 class hashable_dict: def __init__(self, d): self.my_dict = d self.my_frozenset = frozenset(d.items()) def __getitem__(self, item): return self.my_dict[item] def __hash__(self): return hash(self.my_frozenset) def __eq__(self, rhs): return isinstance(rhs, hashable_dict) and self.my_frozenset == rhs.my_frozenset def __ne__(self, rhs): return not self == rhs def __str__(self): return 'hashable_dict(' + str(self.my_dict) + ')' def __repr__(self): return self.__str__() 
+4
source

The following code works well, because by default your class object hashable:

 Class Foo(object): def __init__(self): pass myinstance = Foo() mydict = {myinstance : 'Hello world'} print mydict[myinstance] 

Exit : Hello World

In addition, for more advanced use, you should read this post:

User type object as a dictionary key

+3
source

There is nothing wrong with using an instance as a dictionary key if it follows the rule : the dictionary key must be immutable.

+1
source

All Articles