How to convert Python dict to class object with fields

A Python dict is extremely versatile. However, there might be situations where you want to access the dict as if it were a class object and the keys were its fields. This can be easily done by using a namedtuple. Just give it a name and the use the keys to populate its named fields. Set the values for those fields by passing the values from the dict. It all boils down to a single line.

This example code demonstrates the above:

Advertisements

4 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?

    Like

    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("
              f"department_id={self.department_id}"
              f", department_name={self.department_name}"
              f")"
          )
      

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

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

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

      e = Employee(**dict)

      print(e)

      ~~~~~~
      output:

      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

      Like

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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.