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:

class Struct:
    def __init__(self, **entries):

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

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

post_data = {'username': 'Filnor', 'password': 'foobar'}
data_obj = Struct(**post_data)

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


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.