Printing dictionary values rather than references

Discussion in 'Python' started by Amit Dor-Shifer, Jun 10, 2009.

  1. 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
     
    Amit Dor-Shifer, Jun 10, 2009
    #1
    1. Advertising

  2. Amit Dor-Shifer

    Jeff McNeil Guest

    On Jun 10, 10:19 am, 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.
    >
    > 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
     
    Jeff McNeil, Jun 10, 2009
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Punya Narra
    Replies:
    5
    Views:
    1,701
    Itai Raz
    Feb 17, 2004
  2. Nehal Shah
    Replies:
    6
    Views:
    737
    Jacob Yang [MSFT]
    Nov 14, 2003
  3. Robin Day
    Replies:
    3
    Views:
    4,465
    Alessandro Zifiglio
    Jan 21, 2004
  4. Steve
    Replies:
    4
    Views:
    447
    Steve
    Jan 27, 2006
  5. Replies:
    6
    Views:
    88
    Uri Guttman
    Feb 3, 2007
Loading...

Share This Page