Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Program to Form a Dictionary from an Object of a Class
When working with classes in Python, you often need to convert an object's attributes into a dictionary format. Python provides the __dict__ attribute that automatically creates a dictionary containing all instance attributes of an object.
Basic Example
Here's how to create a dictionary from a class object using the __dict__ attribute ?
class BaseClass:
def __init__(self):
self.A = 32
self.B = 60
my_instance = BaseClass()
print("An instance of the class has been created")
print(my_instance.__dict__)
An instance of the class has been created
{'A': 32, 'B': 60}
Using Constructor Parameters
You can also create a more flexible class that accepts parameters ?
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
student = Student("Alice", 20, "A")
student_dict = student.__dict__
print("Student dictionary:")
print(student_dict)
Student dictionary:
{'name': 'Alice', 'age': 20, 'grade': 'A'}
Using vars() Function
The vars() function provides an alternative way to get the same result ?
class Product:
def __init__(self, name, price, quantity):
self.name = name
self.price = price
self.quantity = quantity
product = Product("Laptop", 999.99, 5)
product_dict = vars(product)
print("Product dictionary using vars():")
print(product_dict)
Product dictionary using vars():
{'name': 'Laptop', 'price': 999.99, 'quantity': 5}
Comparison
| Method | Syntax | Description |
|---|---|---|
__dict__ |
obj.__dict__ |
Direct attribute access |
vars() |
vars(obj) |
Built-in function approach |
Key Points
- The
__dict__attribute contains all instance variables as key-value pairs - Both
__dict__andvars()return the same dictionary - Only instance attributes are included, not class attributes or methods
- The resulting dictionary can be modified independently of the original object
Conclusion
Use obj.__dict__ or vars(obj) to convert any class object into a dictionary. This technique is useful for serialization, debugging, and data processing tasks.
Advertisements
