Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use an object (an instance of a class) as a dictionary key in Python?

I want to use a class instance as a dictionary key, like:

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

Python seems to be not able to handle classes as dictionary key, or am I wrong? In addition, I could use a Tuple-list like [(classinstance, helloworld),...] instead of a dictionary, but that looks very unprofessional. Do you have any clue for fixing that issue?

like image 537
ltsstar Avatar asked Sep 26 '11 19:09

ltsstar


People also ask

Can I use object as dictionary key Python?

Dictionaries in Python Almost any type of value can be used as a dictionary key in Python. You can even use built-in objects like types and functions.

Can an object be a dictionary key?

A dictionary key must be an immutable object. A dictionary value can be any object.

Can you store class instances in a dictionary Python?

Class instances can be stored in attributes of list/dictionary type in other class instances (eg Note instance inside Notebook instance).

How do you make a class object into a dictionary in Python?

By using the __dict__ attribute on an object of a class and attaining the dictionary. All objects in Python have an attribute __dict__, which is a dictionary object containing all attributes defined for that object itself. The mapping of attributes with its values is done to generate a dictionary.


1 Answers

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

Class Foo(object):
    def __init__(self):
        pass

myinstance = Foo()
mydict = {myinstance : 'Hello world'}

print mydict[myinstance]

Output : Hello world

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

Object of custom type as dictionary key

like image 139
Sandro Munda Avatar answered Sep 24 '22 18:09

Sandro Munda