
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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'}