How to convert Python dict to class object with fields

Updated post here:

6 thoughts on “How to convert Python dict to class object with fields

  1. this creates a new class named Employee. what if I implemented my own class of Employee and I want it to be this one?


    1. I was having the same issue, eventually I think I might end up going with this solution

      class Department:
      def init(self, department_id: int = None, department_name=None):
      self.department_id = department_id
      self.department_name = department_name

      def __repr__(self):
          return (
              f", department_name={self.department_name}"

      class Employee:
      def init(self, name: str = None, department: Department = None): = name

          if isinstance(department, {}.__class__):
              self.department = Department(**department)
              self.department = department
      def __repr__(self):
          return f"name={}, department={self.department}"

      dict = {“name”: “joe”, “department”: {“department_id”: 1, “department_name”: “Sales”}}

      e = Employee(**dict)



      name=joe, department=Department(department_id=1, department_name=Sales)

      Not sure how “proper” it is to have isinstance checks in the init method, but it works for me


  2. class objectview(object):
    def init(self, d):
    self.dict = d

    Will return an ‘object’ from a supplied dictionary ‘d’
    This is not a 2-way conversion, to accomplish that, you want to create getters and setters, this requires a wrapper class and use of the getattr() and it’s companion setattr() method. Hope this short converter function answers some of the question though.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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