Printing dictionary values rather than references

Terry Reedy tjreedy at udel.edu
Wed Jun 10 22:22:46 CEST 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.

You can only print string representations, as defined by 
type(ob).__str__ and type(ob).__repr__.

> 
> class MyClass:
>     def __str__(self):
>         return str(self.__dict__)
> 
> if __name__ == '__main__':
>     dict = dict()

Rebinding built-in names is a bad idea unless you *really* mean to 
replace the original.

>     classA = MyClass()
>     setattr(classA, "attr-1", "val-1")
>    
>     dict['a']= classA
>     print classA
>     ''' Desired output: {'attr-1': 'val-1'}'''
>     print dict
>     ''' Actual output: {'a': <__main__.MyClass instance at 0x79cfc8>}'''
> 
> Thanks,
> Amit




More information about the Python-list mailing list