<p>Do you know if there is a built-in function to build a dictionary from an arbitrary object? I'd like to do something like this:</p>

<pre><code>&gt;&gt;&gt; class Foo:
...     bar = 'hello'
...     baz = 'world'
...
&gt;&gt;&gt; f = Foo()
&gt;&gt;&gt; props(f)
{ 'bar' : 'hello', 'baz' : 'world' }
</code></pre>

<p><strong>NOTE:</strong> It should not include methods. Only fields.</p>

[{'answer_id': 61522, 'author': 'dF.', 'author_id': 3002, 'author_profile': 'https://Stackoverflow.com/users/3002', 'pm_score': 6, 'selected': False, 'text': "<p>The <code>dir</code> builtin will give you all the object's attributes, including special methods like <code>__str__</code>, <code>__dict__</code> and a whole bunch of others which you probably don't want. But you can do something like:</p>\n\n<pre><code>&gt;&gt;&gt; class Foo(object):\n...     bar = 'hello'\n...     baz = 'world'\n...\n&gt;&gt;&gt; f = Foo()\n&gt;&gt;&gt; [name for name in dir(f) if not name.startswith('__')]\n[ 'bar', 'baz' ]\n&gt;&gt;&gt; dict((name, getattr(f, name)) for name in dir(f) if not name.startswith('__')) \n{ 'bar': 'hello', 'baz': 'world' }\n</code></pre>\n\n<p>So can extend this to only return data attributes and not methods, by defining your <code>props</code> function like this:</p>\n\n<pre><code>import inspect\n\ndef props(obj):\n    pr = {}\n    for name in dir(obj):\n        value = getattr(obj, name)\n        if not name.startswith('__') and not inspect.ismethod(value):\n            pr[name] = value\n    return pr\n</code></pre>\n"}, {'answer_id': 61551, 'author': 'Julio César', 'author_id': 2148, 'author_profile': 'https://Stackoverflow.com/users/2148', 'pm_score': 5, 'selected': False, 'text': "<p>I've settled with a combination of both answers:</p>\n\n<pre><code>dict((key, value) for key, value in f.__dict__.iteritems() \n    if not callable(value) and not key.startswith('__'))\n</code></pre>\n"}, {'answer_id': 62680, 'author': 'user6868', 'author_id': 6868, 'author_profile': 'https://Stackoverflow.com/users/6868', 'pm_score': 10, 'selected': True, 'text': '<p>Note that best practice in Python 2.7 is to use <em><a href="https://www.python.org/doc/newstyle/" rel="noreferrer">new-style</a></em> classes (not needed with Python 3), i.e.</p>\n\n<pre><code>class Foo(object):\n   ...\n</code></pre>\n\n<p>Also, there\'s a difference between an \'object\' and a \'class\'. To build a dictionary from an arbitrary <em>object</em>, it\'s sufficient to use <code>__dict__</code>. Usually, you\'ll declare your methods at class level and your attributes at instance level, so <code>__dict__</code> should be fine. For example:</p>\n\n<pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; class A(object):\n...   def __init__(self):\n...     self.b = 1\n...     self.c = 2\n...   def do_nothing(self):\n...     pass\n...\n&gt;&gt;&gt; a = A()\n&gt;&gt;&gt; a.__dict__\n{\'c\': 2, \'b\': 1}\n</code></pre>\n\n<p>A better approach (suggested by <a href="https://stackoverflow.com/users/409638/robert">robert</a> in comments) is the builtin <a href="https://docs.python.org/3/library/functions.html#vars" rel="noreferrer"><code>vars</code></a> function:</p>\n\n<pre class="lang-python prettyprint-override"><code>&gt;&gt;&gt; vars(a)\n{\'c\': 2, \'b\': 1}\n</code></pre>\n\n<p>Alternatively, depending on what you want to do, it might be nice to inherit from <code>dict</code>. Then your class is <em>already</em> a dictionary, and if you want you can override <code>getattr</code> and/or <code>setattr</code> to call through and set the dict. For example:</p>\n\n<pre><code>class Foo(dict):\n    def __init__(self):\n        pass\n    def __getattr__(self, attr):\n        return self[attr]\n\n    # etc...\n</code></pre>\n'}, {'answer_id': 63635, 'author': 'indentation', 'author_id': 7706, 'author_profile': 'https://Stackoverflow.com/users/7706', 'pm_score': 4, 'selected': False, 'text': "<blockquote>\n  <p>To build a dictionary from an arbitrary <i>object</i>, it's sufficient to use <code>__dict__</code>.</p>\n</blockquote>\n\n<p>This misses attributes that the object inherits from its class. For example,</p>\n\n<pre><code>class c(object):\n    x = 3\na = c()\n</code></pre>\n\n<p>hasattr(a, 'x') is true, but 'x' does not appear in a.__dict__</p>\n"}, {'answer_id': 17470565, 'author': 'Score_Under', 'author_id': 1091693, 'author_profile': 'https://Stackoverflow.com/users/1091693', 'pm_score': 3, 'selected': False, 'text': '<p>Late answer but provided for completeness and the benefit of googlers:</p>\n\n<pre><code>def props(x):\n    return dict((key, getattr(x, key)) for key in dir(x) if key not in dir(x.__class__))\n</code></pre>\n\n<p>This will not show methods defined in the class, but it will still show fields including those assigned to lambdas or those which start with a double underscore.</p>\n'}, {'answer_id': 23937693, 'author': 'radtek', 'author_id': 2023392, 'author_profile': 'https://Stackoverflow.com/users/2023392', 'pm_score': 3, 'selected': False, 'text': "<p>I think the easiest way is to create a <strong>getitem</strong> attribute for the class. If you need to write to the object, you can create a custom <strong>setattr</strong> . Here is an example for <strong>getitem</strong>:</p>\n\n<pre><code>class A(object):\n    def __init__(self):\n        self.b = 1\n        self.c = 2\n    def __getitem__(self, item):\n        return self.__dict__[item]\n\n# Usage: \na = A()\na.__getitem__('b')  # Outputs 1\na.__dict__  # Outputs {'c': 2, 'b': 1}\nvars(a)  # Outputs {'c': 2, 'b': 1}\n</code></pre>\n\n<p><strong>dict</strong> generates the objects attributes into a dictionary and the dictionary object can be used to get the item you need.</p>\n"}, {'answer_id': 29333136, 'author': 'Seaux', 'author_id': 263175, 'author_profile': 'https://Stackoverflow.com/users/263175', 'pm_score': 5, 'selected': False, 'text': '<p>I thought I\'d take some time to show you how you can translate an object to dict via <code>dict(obj)</code>.</p>\n\n<pre class="lang-py prettyprint-override"><code>class A(object):\n    d = \'4\'\n    e = \'5\'\n    f = \'6\'\n\n    def __init__(self):\n        self.a = \'1\'\n        self.b = \'2\'\n        self.c = \'3\'\n\n    def __iter__(self):\n        # first start by grabbing the Class items\n        iters = dict((x,y) for x,y in A.__dict__.items() if x[:2] != \'__\')\n\n        # then update the class items with the instance items\n        iters.update(self.__dict__)\n\n        # now \'yield\' through the items\n        for x,y in iters.items():\n            yield x,y\n\na = A()\nprint(dict(a)) \n# prints "{\'a\': \'1\', \'c\': \'3\', \'b\': \'2\', \'e\': \'5\', \'d\': \'4\', \'f\': \'6\'}"\n</code></pre>\n\n<p>The key section of this code is the <code>__iter__</code> function. </p>\n\n<p>As the comments explain, the first thing we do is grab the Class items and prevent anything that starts with \'__\'.</p>\n\n<p>Once you\'ve created that <code>dict</code>, then you can use the <code>update</code> dict function and pass in the instance <code>__dict__</code>.</p>\n\n<p>These will give you a complete class+instance dictionary of members. Now all that\'s left is to iterate over them and yield the returns.</p>\n\n<p>Also, if you plan on using this a lot, you can create an <code>@iterable</code> class decorator.</p>\n\n<pre class="lang-py prettyprint-override"><code>def iterable(cls):\n    def iterfn(self):\n        iters = dict((x,y) for x,y in cls.__dict__.items() if x[:2] != \'__\')\n        iters.update(self.__dict__)\n\n        for x,y in iters.items():\n            yield x,y\n\n    cls.__iter__ = iterfn\n    return cls\n\n@iterable\nclass B(object):\n    d = \'d\'\n    e = \'e\'\n    f = \'f\'\n\n    def __init__(self):\n        self.a = \'a\'\n        self.b = \'b\'\n        self.c = \'c\'\n\nb = B()\nprint(dict(b))\n</code></pre>\n'}, {'answer_id': 31770231, 'author': 'Berislav Lopac', 'author_id': 122033, 'author_profile': 'https://Stackoverflow.com/users/122033', 'pm_score': 8, 'selected': False, 'text': "<p>Instead of <code>x.__dict__</code>, it's actually more pythonic to use <code>vars(x)</code>.</p>\n"}, {'answer_id': 34662287, 'author': 'coanor', 'author_id': 342348, 'author_profile': 'https://Stackoverflow.com/users/342348', 'pm_score': 1, 'selected': False, 'text': "<p>If you want to list part of your attributes, override <code>__dict__</code>:</p>\n\n<pre><code>def __dict__(self):\n    d = {\n    'attr_1' : self.attr_1,\n    ...\n    }\n    return d\n\n# Call __dict__\nd = instance.__dict__()\n</code></pre>\n\n<p>This helps a lot if your <code>instance</code> get some large block data and you want to push <code>d</code> to Redis like message queue. </p>\n"}, {'answer_id': 48696573, 'author': 'spattanaik75', 'author_id': 3094089, 'author_profile': 'https://Stackoverflow.com/users/3094089', 'pm_score': 0, 'selected': False, 'text': "<h2>PYTHON 3:</h2>\n\n<pre><code>class DateTimeDecoder(json.JSONDecoder):\n\n   def __init__(self, *args, **kargs):\n        JSONDecoder.__init__(self, object_hook=self.dict_to_object,\n                         *args, **kargs)\n\n   def dict_to_object(self, d):\n       if '__type__' not in d:\n          return d\n\n       type = d.pop('__type__')\n       try:\n          dateobj = datetime(**d)\n          return dateobj\n       except:\n          d['__type__'] = type\n          return d\n\ndef json_default_format(value):\n    try:\n        if isinstance(value, datetime):\n            return {\n                '__type__': 'datetime',\n                'year': value.year,\n                'month': value.month,\n                'day': value.day,\n                'hour': value.hour,\n                'minute': value.minute,\n                'second': value.second,\n                'microsecond': value.microsecond,\n            }\n        if isinstance(value, decimal.Decimal):\n            return float(value)\n        if isinstance(value, Enum):\n            return value.name\n        else:\n            return vars(value)\n    except Exception as e:\n        raise ValueError\n</code></pre>\n\n<p>Now you can use above code inside your own class :</p>\n\n<pre><code>class Foo():\n  def toJSON(self):\n        return json.loads(\n            json.dumps(self, sort_keys=True, indent=4, separators=(',', ': '), default=json_default_format), cls=DateTimeDecoder)\n\n\nFoo().toJSON() \n</code></pre>\n"}, {'answer_id': 53823839, 'author': 'R H', 'author_id': 2169290, 'author_profile': 'https://Stackoverflow.com/users/2169290', 'pm_score': 4, 'selected': False, 'text': '<p>A downside of using <code>__dict__</code> is that it is shallow; it won\'t convert any subclasses to dictionaries.</p>\n\n<p>If you\'re using Python3.5 or higher, you can use <a href="https://jsons.readthedocs.io/en/latest/" rel="noreferrer"><code>jsons</code></a>:</p>\n\n<pre><code>&gt;&gt;&gt; import jsons\n&gt;&gt;&gt; jsons.dump(f)\n{\'bar\': \'hello\', \'baz\': \'world\'}\n</code></pre>\n'}, {'answer_id': 61531302, 'author': 'Ricky Levi', 'author_id': 281965, 'author_profile': 'https://Stackoverflow.com/users/281965', 'pm_score': 3, 'selected': False, 'text': "<p><code>vars()</code> is great, but doesn't work for nested objects of objects</p>\n\n<p>Convert nested object of objects to dict:</p>\n\n<pre><code>def to_dict(self):\n    return json.loads(json.dumps(self, default=lambda o: o.__dict__))\n</code></pre>\n"}, {'answer_id': 65469063, 'author': 'Anakhand', 'author_id': 6117426, 'author_profile': 'https://Stackoverflow.com/users/6117426', 'pm_score': 2, 'selected': False, 'text': '<p>As mentioned in <a href="https://stackoverflow.com/questions/61517/python-dictionary-from-an-objects-fields/65469063#comment102192969_31770231">one of the comments above</a>, <code>vars</code> currently isn\'t universal in that it doesn\'t work for objects with <a href="https://docs.python.org/3/reference/datamodel.html#slots" rel="nofollow noreferrer"><code>__slots__</code></a> instead of a normal <code>__dict__</code>. Moreover, some objecs (e.g., builtins like <code>str</code> or <code>int</code>) have <em>neither</em> a <code>__dict__</code> <em>nor</em> <code>__slots__</code>.</p>\n<p>For now, a more versatile solution could be this:</p>\n<pre class="lang-py prettyprint-override"><code>def instance_attributes(obj: Any) -&gt; Dict[str, Any]:\n    &quot;&quot;&quot;Get a name-to-value dictionary of instance attributes of an arbitrary object.&quot;&quot;&quot;\n    try:\n        return vars(obj)\n    except TypeError:\n        pass\n\n    # object doesn\'t have __dict__, try with __slots__\n    try:\n        slots = obj.__slots__\n    except AttributeError:\n        # doesn\'t have __dict__ nor __slots__, probably a builtin like str or int\n        return {}\n    # collect all slots attributes (some might not be present)\n    attrs = {}\n    for name in slots:\n        try:\n            attrs[name] = getattr(obj, name)\n        except AttributeError:\n            continue\n    return attrs\n</code></pre>\n<p>Example:</p>\n<pre class="lang-py prettyprint-override"><code>class Foo:\n    class_var = &quot;spam&quot;\n\n\nclass Bar:\n    class_var = &quot;eggs&quot;\n    \n    __slots__ = [&quot;a&quot;, &quot;b&quot;]\n</code></pre>\n<pre><code>&gt;&gt;&gt; foo = Foo()\n&gt;&gt;&gt; foo.a = 1\n&gt;&gt;&gt; foo.b = 2\n&gt;&gt;&gt; instance_attributes(foo)\n{\'a\': 1, \'b\': 2}\n\n&gt;&gt;&gt; bar = Bar()\n&gt;&gt;&gt; bar.a = 3\n&gt;&gt;&gt; instance_attributes(bar)\n{\'a\': 3}\n\n&gt;&gt;&gt; instance_attributes(&quot;baz&quot;) \n{}\n\n</code></pre>\n<hr />\n<p>Rant:</p>\n<p>It\'s a pity that this isn\'t built into <code>vars</code> already. Many builtins in Python promise to be &quot;the&quot; solution to a problem but then there\'s always several special cases that aren\'t handled... And one just ends up having to write the code manually in any case.</p>\n'}, {'answer_id': 66727687, 'author': 'Reed Sandberg', 'author_id': 1287091, 'author_profile': 'https://Stackoverflow.com/users/1287091', 'pm_score': 3, 'selected': False, 'text': '<p>In 2021, and for nested objects/dicts/json use pydantic BaseModel - will convert nested dicts and nested json objects to python objects and JSON and vice versa:</p>\n<p><a href="https://pydantic-docs.helpmanual.io/usage/models/" rel="noreferrer">https://pydantic-docs.helpmanual.io/usage/models/</a></p>\n<pre><code>&gt;&gt;&gt; class Foo(BaseModel):\n...     count: int\n...     size: float = None\n... \n&gt;&gt;&gt; \n&gt;&gt;&gt; class Bar(BaseModel):\n...     apple = \'x\'\n...     banana = \'y\'\n... \n&gt;&gt;&gt; \n&gt;&gt;&gt; class Spam(BaseModel):\n...     foo: Foo\n...     bars: List[Bar]\n... \n&gt;&gt;&gt; \n&gt;&gt;&gt; m = Spam(foo={\'count\': 4}, bars=[{\'apple\': \'x1\'}, {\'apple\': \'x2\'}])\n</code></pre>\n<p><strong>Object to dict</strong></p>\n<pre><code>&gt;&gt;&gt; print(m.dict())\n{\'foo\': {\'count\': 4, \'size\': None}, \'bars\': [{\'apple\': \'x1\', \'banana\': \'y\'}, {\'apple\': \'x2\', \'banana\': \'y\'}]}\n</code></pre>\n<p><strong>Object to JSON</strong></p>\n<pre><code>&gt;&gt;&gt; print(m.json())\n{&quot;foo&quot;: {&quot;count&quot;: 4, &quot;size&quot;: null}, &quot;bars&quot;: [{&quot;apple&quot;: &quot;x1&quot;, &quot;banana&quot;: &quot;y&quot;}, {&quot;apple&quot;: &quot;x2&quot;, &quot;banana&quot;: &quot;y&quot;}]}\n</code></pre>\n<p><strong>Dict to object</strong></p>\n<pre><code>&gt;&gt;&gt; spam = Spam.parse_obj({\'foo\': {\'count\': 4, \'size\': None}, \'bars\': [{\'apple\': \'x1\', \'banana\': \'y\'}, {\'apple\': \'x2\', \'banana\': \'y2\'}]})\n&gt;&gt;&gt; spam\nSpam(foo=Foo(count=4, size=None), bars=[Bar(apple=\'x1\', banana=\'y\'), Bar(apple=\'x2\', banana=\'y2\')])\n</code></pre>\n<p><strong>JSON to object</strong></p>\n<pre><code>&gt;&gt;&gt; spam = Spam.parse_raw(\'{&quot;foo&quot;: {&quot;count&quot;: 4, &quot;size&quot;: null}, &quot;bars&quot;: [{&quot;apple&quot;: &quot;x1&quot;, &quot;banana&quot;: &quot;y&quot;}, {&quot;apple&quot;: &quot;x2&quot;, &quot;banana&quot;: &quot;y&quot;}]}\')\n&gt;&gt;&gt; spam\nSpam(foo=Foo(count=4, size=None), bars=[Bar(apple=\'x1\', banana=\'y\'), Bar(apple=\'x2\', banana=\'y\')])\n</code></pre>\n'}, {'answer_id': 68982164, 'author': 'thetaprime', 'author_id': 1968839, 'author_profile': 'https://Stackoverflow.com/users/1968839', 'pm_score': 0, 'selected': False, 'text': '<p>Try:</p>\n<pre class="lang-py prettyprint-override"><code>from pprint import pformat\na_dict = eval(pformat(an_obj))\n</code></pre>\n'}, {'answer_id': 69088860, 'author': 'hizbul25', 'author_id': 1534638, 'author_profile': 'https://Stackoverflow.com/users/1534638', 'pm_score': 3, 'selected': False, 'text': "<p><strong>Python3.x</strong></p>\n<pre><code>return dict((key, value) for key, value in f.__dict__.items() if not callable(value) and not key.startswith('__'))\n</code></pre>\n"}, {'answer_id': 73388990, 'author': 'Surya Teja', 'author_id': 5692181, 'author_profile': 'https://Stackoverflow.com/users/5692181', 'pm_score': 2, 'selected': False, 'text': '<p>Dataclass(from Python 3.7) is another option which can be used for converting class properties to dict. <a href="https://docs.python.org/3/library/dataclasses.html#dataclasses.asdict" rel="nofollow noreferrer">asdict</a> can be used along with dataclass objects\nfor the conversion.</p>\n<p>Example:</p>\n<pre><code>@dataclass\nclass Point:\n   x: int\n   y: int\n\np = Point(10, 20)\nasdict(p) # it returns {\'x\': 10, \'y\': 20}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/61517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2148/']