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?
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.
A dictionary key must be an immutable object. A dictionary value can be any object.
Class instances can be stored in attributes of list/dictionary type in other class instances (eg Note instance inside Notebook instance).
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.
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
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