Skip to content
Advertisement

Python dictionary from an object’s fields

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:

JavaScript

NOTE: It should not include methods. Only fields.

Advertisement

Answer

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

JavaScript

Also, there’s a difference between an ‘object’ and a ‘class’. To build a dictionary from an arbitrary object, it’s sufficient to use __dict__. Usually, you’ll declare your methods at class level and your attributes at instance level, so __dict__ should be fine. For example:

JavaScript

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

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement