Create Python Dictionary from Object's Fields



In Python, objects are instances of classes containing attributes and methods, while dictionaries are collections of key-value pairs. We can obtain a dictionary from an object's fields -

Using __dict__

You can access an object's attributes as a dictionary using its _dict_ attribute. In Python, every object has a _dict_ attribute that stores the object's attributes and their values as a dictionary (key-value pairs).

Example

In this example, we have defined a class Company with attributes Companyname and Location, and created an object "a" with specific values. Using a.__dict__, we are printing the object's attributes as a dictionary.

class Company:
   def __init__(self, Companyname, Location):
      self.Companyname = Companyname
      self.Location = Location

a = Company("Tutorialspoint", "Hyderabad")
print(a.__dict__)

Output

{'Companyname': 'Tutorialspoint', 'Location': 'Hyderabad'}

Using vars()

You can access an object's attributes as a dictionary using vars(). The vars() function returns the dict attribute of an object. The dict attribute is a dictionary that contains attributes and their values.

Example

In this example, we have defined a class Company with attributes Companyname and Location, and created an object "a" with specific values. Using a vars(), we are printing the object's attributes as a dictionary.

class Company:
   def __init__(self, Companyname, Location):
      self.Companyname = Companyname
      self.Location = Location

a = Company("Tutorialspoint", "Hyderabad")
print(vars(a))

Output

{'Companyname': 'Tutorialspoint', 'Location': 'Hyderabad'}
Updated on: 2025-05-20T16:12:44+05:30

340 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements