Python dictionary from an objects fields

Python dictionary from an objects fields

Note that best practice in Python 2.7 is to use new-style classes (not needed with Python 3), i.e.

class Foo(object):
   ...

Also, theres a difference between an object and a class. To build a dictionary from an arbitrary object, its sufficient to use __dict__. Usually, youll declare your methods at class level and your attributes at instance level, so __dict__ should be fine. For example:

>>> class A(object):
...   def __init__(self):
...     self.b = 1
...     self.c = 2
...   def do_nothing(self):
...     pass
...
>>> a = A()
>>> a.__dict__
{c: 2, b: 1}

A better approach (suggested by robert in comments) is the builtin vars function:

>>> vars(a)
{c: 2, b: 1}

Alternatively, depending on what you want to do, it might be nice to inherit from dict. Then your class is already a dictionary, and if you want you can override getattr and/or setattr to call through and set the dict. For example:

class Foo(dict):
    def __init__(self):
        pass
    def __getattr__(self, attr):
        return self[attr]

    # etc...

Instead of x.__dict__, its actually more pythonic to use vars(x).

Python dictionary from an objects fields

The dir builtin will give you all the objects attributes, including special methods like __str__, __dict__ and a whole bunch of others which you probably dont want. But you can do something like:

>>> class Foo(object):
...     bar = hello
...     baz = world
...
>>> f = Foo()
>>> [name for name in dir(f) if not name.startswith(__)]
[ bar, baz ]
>>> dict((name, getattr(f, name)) for name in dir(f) if not name.startswith(__)) 
{ bar: hello, baz: world }

So can extend this to only return data attributes and not methods, by defining your props function like this:

import inspect

def props(obj):
    pr = {}
    for name in dir(obj):
        value = getattr(obj, name)
        if not name.startswith(__) and not inspect.ismethod(value):
            pr[name] = value
    return pr

Leave a Reply

Your email address will not be published. Required fields are marked *