Skip to content

Convert Python dict to an object

Related Post: Convert Python object to dict

Sometimes you may have a dict (for example from a POST request) that you want to convert to an object for better code readability and overview.

To do this, you can create a Struct class with this init method:

Note that you can place this class very well to you collection of generic methods (I usually create a new file called utils.py for that).

To use the above class, we’ll convert an example dict to an object:

If you now would print the value of data_obj.username, you would receive the value 'Filnor'.

[sc name=”src” url=”https://stackoverflow.com/questions/1305532/convert-nested-python-dict-to-object” ]

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.