Monday, January 23, 2012

Python: Convert Object to Dictionary

I recently had to explain how you can convert a Python Object to a Python Dictionary.
The answer is surprisingly simple :

class testclass:
        first = str()
        second = str()
        third = str()
        def __init__(self):
                self.first  = 'Some'
                self.second = 'weird'
                self.third  = 'test'

test = testclass()
print test.__dict__

As you probably guest, the answer is hidden in the last line.

2 comments:

  1. What if there is another object within your current object.

    ReplyDelete
    Replies
    1. There are several approaches for such a scenario.
      An very easy solution is following to simply implement your own conversion function inside your class.
      Below example is not the best approach regarding code design but it is easier to understand this way around:

      1 │import datetime
      2 │
      4 │
      5 │class testclass2()
      6 │ someproperty = str()
      7 │ anotherproperty = datetime.datetime.now()
      8 │
      9 │ def __init__(self):
      10 │ self.someproperty = 'a string'
      11 │ self.anotherproperty = datetime.datetime.now()
      12 │
      13 │ def asDict(self):
      14 │ return self.__dict__
      15 │
      16 │
      17 │
      18 │class testclass1() :
      19 │ first = str()
      20 │ second = str()
      21 │ third = datetime.datetime.now()
      22 │ forth = testclass2()
      23 │
      24 │ def __init__(self):
      25 │ self.first = 'a string'
      26 │ self.second = 'second string'
      27 │ self.third = datetime.datetime.now()
      28 │ self.forth = testclass2()
      29 │
      30 │ def asDict(self):
      31 │ returnval = self.__dict__
      32 │ returnval['forth'] = self.forth.asDict()
      33 │ return returnval
      34 │
      35 │
      36 │test = testclass1()
      37 │print test.asDict()

      Delete