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
How to create a Python dictionary from an object\'s fields?
In Python, objects are instances of classes containing attributes and methods, while dictionaries are collections of key-value pairs. Converting an object's fields to a dictionary is useful for serialization, debugging, or data processing. Python provides two main approaches for this conversion.
Using __dict__ Attribute
Every Python object has a __dict__ attribute that stores the object's attributes and their values as a dictionary. This attribute directly exposes the internal namespace of the object ?
Example
class Company:
def __init__(self, company_name, location):
self.company_name = company_name
self.location = location
self.founded_year = 2008
company = Company("TutorialsPoint", "Hyderabad")
print(company.__dict__)
The output of the above code is ?
{'company_name': 'TutorialsPoint', 'location': 'Hyderabad', 'founded_year': 2008}
Using vars() Function
The vars() function returns the __dict__ attribute of an object. It provides a cleaner way to access object attributes as a dictionary ?
Example
class Employee:
def __init__(self, name, department, salary):
self.name = name
self.department = department
self.salary = salary
employee = Employee("John Doe", "Engineering", 75000)
employee_dict = vars(employee)
print(employee_dict)
The output of the above code is ?
{'name': 'John Doe', 'department': 'Engineering', 'salary': 75000}
Comparison
| Method | Syntax | Readability | Use Case |
|---|---|---|---|
__dict__ |
obj.__dict__ |
Less clean | Direct attribute access |
vars() |
vars(obj) |
More readable | Function-based approach |
Working with Complex Objects
Both methods work with objects containing various data types ?
class Product:
def __init__(self, name, price, categories):
self.name = name
self.price = price
self.categories = categories
self.in_stock = True
product = Product("Laptop", 999.99, ["Electronics", "Computers"])
print("Using __dict__:", product.__dict__)
print("Using vars():", vars(product))
The output of the above code is ?
Using __dict__: {'name': 'Laptop', 'price': 999.99, 'categories': ['Electronics', 'Computers'], 'in_stock': True}
Using vars(): {'name': 'Laptop', 'price': 999.99, 'categories': ['Electronics', 'Computers'], 'in_stock': True}
Conclusion
Both __dict__ and vars() provide access to an object's attributes as a dictionary. Use vars() for cleaner, more readable code, while __dict__ offers direct attribute access when needed.
