Create Python Dictionary from Object's Fields



The __dict__ attribute returns a dictionary out of fields of any object.

Let us define a class person

>>> class person:
def __init__(self):
   self.name='foo'
   self.age = 20
def show(self):
   print (self.name, self.age)

We now declare an object of this class and obtain its __dict__ attribute which turns out to be dictionary object

>>> p = person()
>>> d = p.__dict__
>>> d
{'name': 'foo', 'age': 20}
Updated on: 2019-07-30T22:30:21+05:30

318 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements