Printing dictionary values rather than references

A

Amit Dor-Shifer

Hi all.

I'd like to print-out a dictionary of objects. The printed values are
references. How Do I print the actual objects.

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

if __name__ == '__main__':
dict = dict()
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
 
J

Jeff McNeil

Hi all.

I'd like to print-out a dictionary of objects. The printed values are
references. How Do I print the actual objects.

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

if __name__ == '__main__':
    dict = dict()
    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

class MyClass:
def __repr__(self): # <--- see http://docs.python.org/library/functions..html#repr
return str(self.__dict__)
HTH,

Jeff
mcjeff.blogspot.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top