Skip to content

Convert Python object to dict

Related Post: Convert Python dict to an object

Especially in programming REST APIs, you’ll find yourselves stuck up needing to return an object, which Python can’t automatically convert to a dict automatically (for example for a JSON response).

But there is a (hackish) workaround for this, creating a as_dictmethod. In that method, you return a dict where each value of the object properties gets retrieved using self:

Be First to Comment

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.