Printing dictionary values rather than references

Ben Charrow bcharrow at csail.mit.edu
Wed Jun 10 11:16:56 EDT 2009


Amit Dor-Shifer wrote:
> Hi all.
> 
> I'd like to print-out a dictionary of objects. The printed values are
> references. How Do I print the actual objects.
> 
> Thanks,
> Amit

How about this:

class MyClass:
    def __str__(self):
        return str(self.__dict__)

    def __repr__(self):
        return str(self.__dict__)

if __name__ == '__main__':
    my_dict = dict()
    classA = MyClass()
    setattr(classA, "attr-1", "val-1")

    my_dict['a']= classA
    print my_dict
    ''' Actual output: {'attr-1': 'val-1'}'''

Though I'm guessing someone is going to say that this is not how repr is
supposed be used.  See this for more information:

http://docs.python.org/reference/datamodel.html#object.__repr__

Cheers,
Ben



More information about the Python-list mailing list