Question

In Python, using custom objects as dictionary keys can give pretty unreadable output. This is a small example:

class myClass(object):
    def __init__(self,foo,bar):
        self.foo = foo
        self.bar = bar

item = myClass(1,2)
myDict = {}
myDict[item] = 10 

print myDict
{<__main__.myClass object at 0x01998FD0>: 10}

This dictionary will become unreadable if there are many objects. I would like it to show the name of the object instead:

{'item':10}

How to achieve this?

Was it helpful?

Solution

Define __repr__ for myClass:

>>> class myClass(object):
...     def __init__(self,foo,bar):
...         self.foo = foo
...         self.bar = bar
...     def __repr__(self):
...         return 'myClass({0.foo},{0.bar})'.format(self)
... 
>>> item = myClass(1,2)
>>> item
myClass(1,2)
>>> myDict = {}
>>> myDict[item] = 10
>>> myDict
{myClass(1,2): 10}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top